babylon.max.js 3.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141
  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. return KeyboardEventTypes;
  37. }());
  38. KeyboardEventTypes._KEYDOWN = 0x01;
  39. KeyboardEventTypes._KEYUP = 0x02;
  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. return PointerEventTypes;
  120. }());
  121. PointerEventTypes._POINTERDOWN = 0x01;
  122. PointerEventTypes._POINTERUP = 0x02;
  123. PointerEventTypes._POINTERMOVE = 0x04;
  124. PointerEventTypes._POINTERWHEEL = 0x08;
  125. PointerEventTypes._POINTERPICK = 0x10;
  126. PointerEventTypes._POINTERTAP = 0x20;
  127. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  128. BABYLON.PointerEventTypes = PointerEventTypes;
  129. var PointerInfoBase = (function () {
  130. function PointerInfoBase(type, event) {
  131. this.type = type;
  132. this.event = event;
  133. }
  134. return PointerInfoBase;
  135. }());
  136. BABYLON.PointerInfoBase = PointerInfoBase;
  137. /**
  138. * This class is used to store pointer related info for the onPrePointerObservable event.
  139. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  140. */
  141. var PointerInfoPre = (function (_super) {
  142. __extends(PointerInfoPre, _super);
  143. function PointerInfoPre(type, event, localX, localY) {
  144. var _this = _super.call(this, type, event) || this;
  145. _this.skipOnPointerObservable = false;
  146. _this.localPosition = new BABYLON.Vector2(localX, localY);
  147. return _this;
  148. }
  149. return PointerInfoPre;
  150. }(PointerInfoBase));
  151. BABYLON.PointerInfoPre = PointerInfoPre;
  152. /**
  153. * This type contains all the data related to a pointer event in Babylon.js.
  154. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  155. */
  156. var PointerInfo = (function (_super) {
  157. __extends(PointerInfo, _super);
  158. function PointerInfo(type, event, pickInfo) {
  159. var _this = _super.call(this, type, event) || this;
  160. _this.pickInfo = pickInfo;
  161. return _this;
  162. }
  163. return PointerInfo;
  164. }(PointerInfoBase));
  165. BABYLON.PointerInfo = PointerInfo;
  166. })(BABYLON || (BABYLON = {}));
  167. //# sourceMappingURL=babylon.pointerEvents.js.map
  168. var BABYLON;
  169. (function (BABYLON) {
  170. BABYLON.ToGammaSpace = 1 / 2.2;
  171. BABYLON.ToLinearSpace = 2.2;
  172. BABYLON.Epsilon = 0.001;
  173. var Color3 = (function () {
  174. /**
  175. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  176. */
  177. function Color3(r, g, b) {
  178. if (r === void 0) { r = 0; }
  179. if (g === void 0) { g = 0; }
  180. if (b === void 0) { b = 0; }
  181. this.r = r;
  182. this.g = g;
  183. this.b = b;
  184. }
  185. /**
  186. * Returns a string with the Color3 current values.
  187. */
  188. Color3.prototype.toString = function () {
  189. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  190. };
  191. /**
  192. * Returns the string "Color3".
  193. */
  194. Color3.prototype.getClassName = function () {
  195. return "Color3";
  196. };
  197. /**
  198. * Returns the Color3 hash code.
  199. */
  200. Color3.prototype.getHashCode = function () {
  201. var hash = this.r || 0;
  202. hash = (hash * 397) ^ (this.g || 0);
  203. hash = (hash * 397) ^ (this.b || 0);
  204. return hash;
  205. };
  206. // Operators
  207. /**
  208. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  209. * Returns the Color3.
  210. */
  211. Color3.prototype.toArray = function (array, index) {
  212. if (index === undefined) {
  213. index = 0;
  214. }
  215. array[index] = this.r;
  216. array[index + 1] = this.g;
  217. array[index + 2] = this.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color4 object from the current Color3 and the passed alpha.
  222. */
  223. Color3.prototype.toColor4 = function (alpha) {
  224. if (alpha === void 0) { alpha = 1; }
  225. return new Color4(this.r, this.g, this.b, alpha);
  226. };
  227. /**
  228. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  229. */
  230. Color3.prototype.asArray = function () {
  231. var result = [];
  232. this.toArray(result, 0);
  233. return result;
  234. };
  235. /**
  236. * Returns the luminance value (float).
  237. */
  238. Color3.prototype.toLuminance = function () {
  239. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  240. };
  241. /**
  242. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  243. * Returns this new object.
  244. */
  245. Color3.prototype.multiply = function (otherColor) {
  246. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  247. };
  248. /**
  249. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  250. * Returns the current Color3.
  251. */
  252. Color3.prototype.multiplyToRef = function (otherColor, result) {
  253. result.r = this.r * otherColor.r;
  254. result.g = this.g * otherColor.g;
  255. result.b = this.b * otherColor.b;
  256. return this;
  257. };
  258. /**
  259. * Boolean : True if the rgb values are equal to the passed ones.
  260. */
  261. Color3.prototype.equals = function (otherColor) {
  262. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  263. };
  264. /**
  265. * Boolean : True if the rgb values are equal to the passed ones.
  266. */
  267. Color3.prototype.equalsFloats = function (r, g, b) {
  268. return this.r === r && this.g === g && this.b === b;
  269. };
  270. /**
  271. * Multiplies in place each rgb value by scale.
  272. * Returns the updated Color3.
  273. */
  274. Color3.prototype.scale = function (scale) {
  275. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  276. };
  277. /**
  278. * Multiplies the rgb values by scale and stores the result into "result".
  279. * Returns the unmodified current Color3.
  280. */
  281. Color3.prototype.scaleToRef = function (scale, result) {
  282. result.r = this.r * scale;
  283. result.g = this.g * scale;
  284. result.b = this.b * scale;
  285. return this;
  286. };
  287. /**
  288. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  289. */
  290. Color3.prototype.add = function (otherColor) {
  291. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  292. };
  293. /**
  294. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  295. * Returns the unmodified current Color3.
  296. */
  297. Color3.prototype.addToRef = function (otherColor, result) {
  298. result.r = this.r + otherColor.r;
  299. result.g = this.g + otherColor.g;
  300. result.b = this.b + otherColor.b;
  301. return this;
  302. };
  303. /**
  304. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  305. */
  306. Color3.prototype.subtract = function (otherColor) {
  307. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  308. };
  309. /**
  310. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  311. * Returns the unmodified current Color3.
  312. */
  313. Color3.prototype.subtractToRef = function (otherColor, result) {
  314. result.r = this.r - otherColor.r;
  315. result.g = this.g - otherColor.g;
  316. result.b = this.b - otherColor.b;
  317. return this;
  318. };
  319. /**
  320. * Returns a new Color3 copied the current one.
  321. */
  322. Color3.prototype.clone = function () {
  323. return new Color3(this.r, this.g, this.b);
  324. };
  325. /**
  326. * Copies the rgb values from the source in the current Color3.
  327. * Returns the updated Color3.
  328. */
  329. Color3.prototype.copyFrom = function (source) {
  330. this.r = source.r;
  331. this.g = source.g;
  332. this.b = source.b;
  333. return this;
  334. };
  335. /**
  336. * Updates the Color3 rgb values from the passed floats.
  337. * Returns the Color3.
  338. */
  339. Color3.prototype.copyFromFloats = function (r, g, b) {
  340. this.r = r;
  341. this.g = g;
  342. this.b = b;
  343. return this;
  344. };
  345. /**
  346. * Updates the Color3 rgb values from the passed floats.
  347. * Returns the Color3.
  348. */
  349. Color3.prototype.set = function (r, g, b) {
  350. return this.copyFromFloats(r, g, b);
  351. };
  352. /**
  353. * Returns the Color3 hexadecimal code as a string.
  354. */
  355. Color3.prototype.toHexString = function () {
  356. var intR = (this.r * 255) | 0;
  357. var intG = (this.g * 255) | 0;
  358. var intB = (this.b * 255) | 0;
  359. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  360. };
  361. /**
  362. * Returns a new Color3 converted to linear space.
  363. */
  364. Color3.prototype.toLinearSpace = function () {
  365. var convertedColor = new Color3();
  366. this.toLinearSpaceToRef(convertedColor);
  367. return convertedColor;
  368. };
  369. /**
  370. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  371. * Returns the unmodified Color3.
  372. */
  373. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  374. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  375. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  376. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  377. return this;
  378. };
  379. /**
  380. * Returns a new Color3 converted to gamma space.
  381. */
  382. Color3.prototype.toGammaSpace = function () {
  383. var convertedColor = new Color3();
  384. this.toGammaSpaceToRef(convertedColor);
  385. return convertedColor;
  386. };
  387. /**
  388. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  389. * Returns the unmodified Color3.
  390. */
  391. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  392. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  393. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  394. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  395. return this;
  396. };
  397. // Statics
  398. /**
  399. * Creates a new Color3 from the string containing valid hexadecimal values.
  400. */
  401. Color3.FromHexString = function (hex) {
  402. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  403. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  404. return new Color3(0, 0, 0);
  405. }
  406. var r = parseInt(hex.substring(1, 3), 16);
  407. var g = parseInt(hex.substring(3, 5), 16);
  408. var b = parseInt(hex.substring(5, 7), 16);
  409. return Color3.FromInts(r, g, b);
  410. };
  411. /**
  412. * Creates a new Vector3 from the startind index of the passed array.
  413. */
  414. Color3.FromArray = function (array, offset) {
  415. if (offset === void 0) { offset = 0; }
  416. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  417. };
  418. /**
  419. * Creates a new Color3 from integer values ( < 256).
  420. */
  421. Color3.FromInts = function (r, g, b) {
  422. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  423. };
  424. /**
  425. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  426. */
  427. Color3.Lerp = function (start, end, amount) {
  428. var r = start.r + ((end.r - start.r) * amount);
  429. var g = start.g + ((end.g - start.g) * amount);
  430. var b = start.b + ((end.b - start.b) * amount);
  431. return new Color3(r, g, b);
  432. };
  433. Color3.Red = function () { return new Color3(1, 0, 0); };
  434. Color3.Green = function () { return new Color3(0, 1, 0); };
  435. Color3.Blue = function () { return new Color3(0, 0, 1); };
  436. Color3.Black = function () { return new Color3(0, 0, 0); };
  437. Color3.White = function () { return new Color3(1, 1, 1); };
  438. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  439. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  440. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  441. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  442. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  443. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  444. return Color3;
  445. }());
  446. BABYLON.Color3 = Color3;
  447. var Color4 = (function () {
  448. /**
  449. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  450. */
  451. function Color4(r, g, b, a) {
  452. if (r === void 0) { r = 0; }
  453. if (g === void 0) { g = 0; }
  454. if (b === void 0) { b = 0; }
  455. if (a === void 0) { a = 1; }
  456. this.r = r;
  457. this.g = g;
  458. this.b = b;
  459. this.a = a;
  460. }
  461. // Operators
  462. /**
  463. * Adds in place the passed Color4 values to the current Color4.
  464. * Returns the updated Color4.
  465. */
  466. Color4.prototype.addInPlace = function (right) {
  467. this.r += right.r;
  468. this.g += right.g;
  469. this.b += right.b;
  470. this.a += right.a;
  471. return this;
  472. };
  473. /**
  474. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  475. */
  476. Color4.prototype.asArray = function () {
  477. var result = [];
  478. this.toArray(result, 0);
  479. return result;
  480. };
  481. /**
  482. * Stores from the starting index in the passed array the Color4 successive values.
  483. * Returns the Color4.
  484. */
  485. Color4.prototype.toArray = function (array, index) {
  486. if (index === undefined) {
  487. index = 0;
  488. }
  489. array[index] = this.r;
  490. array[index + 1] = this.g;
  491. array[index + 2] = this.b;
  492. array[index + 3] = this.a;
  493. return this;
  494. };
  495. /**
  496. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  497. */
  498. Color4.prototype.add = function (right) {
  499. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  500. };
  501. /**
  502. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  503. */
  504. Color4.prototype.subtract = function (right) {
  505. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  506. };
  507. /**
  508. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  509. * Returns the Color4.
  510. */
  511. Color4.prototype.subtractToRef = function (right, result) {
  512. result.r = this.r - right.r;
  513. result.g = this.g - right.g;
  514. result.b = this.b - right.b;
  515. result.a = this.a - right.a;
  516. return this;
  517. };
  518. /**
  519. * Creates a new Color4 with the current Color4 values multiplied by scale.
  520. */
  521. Color4.prototype.scale = function (scale) {
  522. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  523. };
  524. /**
  525. * Multiplies the current Color4 values by scale and stores the result in "result".
  526. * Returns the Color4.
  527. */
  528. Color4.prototype.scaleToRef = function (scale, result) {
  529. result.r = this.r * scale;
  530. result.g = this.g * scale;
  531. result.b = this.b * scale;
  532. result.a = this.a * scale;
  533. return this;
  534. };
  535. /**
  536. * Multipy an RGBA Color4 value by another and return a new Color4 object
  537. * @param color The Color4 (RGBA) value to multiply by
  538. * @returns A new Color4.
  539. */
  540. Color4.prototype.multiply = function (color) {
  541. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  542. };
  543. /**
  544. * Multipy an RGBA Color4 value by another and push the result in a reference value
  545. * @param color The Color4 (RGBA) value to multiply by
  546. * @param result The Color4 (RGBA) to fill the result in
  547. * @returns the result Color4.
  548. */
  549. Color4.prototype.multiplyToRef = function (color, result) {
  550. result.r = this.r * color.r;
  551. result.g = this.g * color.g;
  552. result.b = this.b * color.b;
  553. result.a = this.a * color.a;
  554. return result;
  555. };
  556. /**
  557. * Returns a string with the Color4 values.
  558. */
  559. Color4.prototype.toString = function () {
  560. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  561. };
  562. /**
  563. * Returns the string "Color4"
  564. */
  565. Color4.prototype.getClassName = function () {
  566. return "Color4";
  567. };
  568. /**
  569. * Return the Color4 hash code as a number.
  570. */
  571. Color4.prototype.getHashCode = function () {
  572. var hash = this.r || 0;
  573. hash = (hash * 397) ^ (this.g || 0);
  574. hash = (hash * 397) ^ (this.b || 0);
  575. hash = (hash * 397) ^ (this.a || 0);
  576. return hash;
  577. };
  578. /**
  579. * Creates a new Color4 copied from the current one.
  580. */
  581. Color4.prototype.clone = function () {
  582. return new Color4(this.r, this.g, this.b, this.a);
  583. };
  584. /**
  585. * Copies the passed Color4 values into the current one.
  586. * Returns the updated Color4.
  587. */
  588. Color4.prototype.copyFrom = function (source) {
  589. this.r = source.r;
  590. this.g = source.g;
  591. this.b = source.b;
  592. this.a = source.a;
  593. return this;
  594. };
  595. /**
  596. * Copies the passed float values into the current one.
  597. * Returns the updated Color4.
  598. */
  599. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  600. this.r = r;
  601. this.g = g;
  602. this.b = b;
  603. this.a = a;
  604. return this;
  605. };
  606. /**
  607. * Copies the passed float values into the current one.
  608. * Returns the updated Color4.
  609. */
  610. Color4.prototype.set = function (r, g, b, a) {
  611. return this.copyFromFloats(r, g, b, a);
  612. };
  613. /**
  614. * Returns a string containing the hexadecimal Color4 code.
  615. */
  616. Color4.prototype.toHexString = function () {
  617. var intR = (this.r * 255) | 0;
  618. var intG = (this.g * 255) | 0;
  619. var intB = (this.b * 255) | 0;
  620. var intA = (this.a * 255) | 0;
  621. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  622. };
  623. /**
  624. * Returns a new Color4 converted to linear space.
  625. */
  626. Color4.prototype.toLinearSpace = function () {
  627. var convertedColor = new Color4();
  628. this.toLinearSpaceToRef(convertedColor);
  629. return convertedColor;
  630. };
  631. /**
  632. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  633. * Returns the unmodified Color4.
  634. */
  635. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  636. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  637. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  638. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  639. convertedColor.a = this.a;
  640. return this;
  641. };
  642. /**
  643. * Returns a new Color4 converted to gamma space.
  644. */
  645. Color4.prototype.toGammaSpace = function () {
  646. var convertedColor = new Color4();
  647. this.toGammaSpaceToRef(convertedColor);
  648. return convertedColor;
  649. };
  650. /**
  651. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  652. * Returns the unmodified Color4.
  653. */
  654. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  655. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  656. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  657. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  658. convertedColor.a = this.a;
  659. return this;
  660. };
  661. // Statics
  662. /**
  663. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  664. */
  665. Color4.FromHexString = function (hex) {
  666. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  667. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  668. return new Color4(0.0, 0.0, 0.0, 0.0);
  669. }
  670. var r = parseInt(hex.substring(1, 3), 16);
  671. var g = parseInt(hex.substring(3, 5), 16);
  672. var b = parseInt(hex.substring(5, 7), 16);
  673. var a = parseInt(hex.substring(7, 9), 16);
  674. return Color4.FromInts(r, g, b, a);
  675. };
  676. /**
  677. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  678. */
  679. Color4.Lerp = function (left, right, amount) {
  680. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  681. Color4.LerpToRef(left, right, amount, result);
  682. return result;
  683. };
  684. /**
  685. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  686. */
  687. Color4.LerpToRef = function (left, right, amount, result) {
  688. result.r = left.r + (right.r - left.r) * amount;
  689. result.g = left.g + (right.g - left.g) * amount;
  690. result.b = left.b + (right.b - left.b) * amount;
  691. result.a = left.a + (right.a - left.a) * amount;
  692. };
  693. /**
  694. * Creates a new Color4 from the starting index element of the passed array.
  695. */
  696. Color4.FromArray = function (array, offset) {
  697. if (offset === void 0) { offset = 0; }
  698. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  699. };
  700. /**
  701. * Creates a new Color4 from the passed integers ( < 256 ).
  702. */
  703. Color4.FromInts = function (r, g, b, a) {
  704. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  705. };
  706. Color4.CheckColors4 = function (colors, count) {
  707. // Check if color3 was used
  708. if (colors.length === count * 3) {
  709. var colors4 = [];
  710. for (var index = 0; index < colors.length; index += 3) {
  711. var newIndex = (index / 3) * 4;
  712. colors4[newIndex] = colors[index];
  713. colors4[newIndex + 1] = colors[index + 1];
  714. colors4[newIndex + 2] = colors[index + 2];
  715. colors4[newIndex + 3] = 1.0;
  716. }
  717. return colors4;
  718. }
  719. return colors;
  720. };
  721. return Color4;
  722. }());
  723. BABYLON.Color4 = Color4;
  724. var Vector2 = (function () {
  725. /**
  726. * Creates a new Vector2 from the passed x and y coordinates.
  727. */
  728. function Vector2(x, y) {
  729. this.x = x;
  730. this.y = y;
  731. }
  732. /**
  733. * Returns a string with the Vector2 coordinates.
  734. */
  735. Vector2.prototype.toString = function () {
  736. return "{X: " + this.x + " Y:" + this.y + "}";
  737. };
  738. /**
  739. * Returns the string "Vector2"
  740. */
  741. Vector2.prototype.getClassName = function () {
  742. return "Vector2";
  743. };
  744. /**
  745. * Returns the Vector2 hash code as a number.
  746. */
  747. Vector2.prototype.getHashCode = function () {
  748. var hash = this.x || 0;
  749. hash = (hash * 397) ^ (this.y || 0);
  750. return hash;
  751. };
  752. // Operators
  753. /**
  754. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  755. * Returns the Vector2.
  756. */
  757. Vector2.prototype.toArray = function (array, index) {
  758. if (index === void 0) { index = 0; }
  759. array[index] = this.x;
  760. array[index + 1] = this.y;
  761. return this;
  762. };
  763. /**
  764. * Returns a new array with 2 elements : the Vector2 coordinates.
  765. */
  766. Vector2.prototype.asArray = function () {
  767. var result = [];
  768. this.toArray(result, 0);
  769. return result;
  770. };
  771. /**
  772. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  773. * Returns the updated Vector2.
  774. */
  775. Vector2.prototype.copyFrom = function (source) {
  776. this.x = source.x;
  777. this.y = source.y;
  778. return this;
  779. };
  780. /**
  781. * Sets the Vector2 coordinates with the passed floats.
  782. * Returns the updated Vector2.
  783. */
  784. Vector2.prototype.copyFromFloats = function (x, y) {
  785. this.x = x;
  786. this.y = y;
  787. return this;
  788. };
  789. /**
  790. * Sets the Vector2 coordinates with the passed floats.
  791. * Returns the updated Vector2.
  792. */
  793. Vector2.prototype.set = function (x, y) {
  794. return this.copyFromFloats(x, y);
  795. };
  796. /**
  797. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  798. */
  799. Vector2.prototype.add = function (otherVector) {
  800. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  801. };
  802. /**
  803. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  804. * Returns the Vector2.
  805. */
  806. Vector2.prototype.addToRef = function (otherVector, result) {
  807. result.x = this.x + otherVector.x;
  808. result.y = this.y + otherVector.y;
  809. return this;
  810. };
  811. /**
  812. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  813. * Returns the updated Vector2.
  814. */
  815. Vector2.prototype.addInPlace = function (otherVector) {
  816. this.x += otherVector.x;
  817. this.y += otherVector.y;
  818. return this;
  819. };
  820. /**
  821. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  822. */
  823. Vector2.prototype.addVector3 = function (otherVector) {
  824. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  825. };
  826. /**
  827. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  828. */
  829. Vector2.prototype.subtract = function (otherVector) {
  830. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  831. };
  832. /**
  833. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  834. * Returns the Vector2.
  835. */
  836. Vector2.prototype.subtractToRef = function (otherVector, result) {
  837. result.x = this.x - otherVector.x;
  838. result.y = this.y - otherVector.y;
  839. return this;
  840. };
  841. /**
  842. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  843. * Returns the updated Vector2.
  844. */
  845. Vector2.prototype.subtractInPlace = function (otherVector) {
  846. this.x -= otherVector.x;
  847. this.y -= otherVector.y;
  848. return this;
  849. };
  850. /**
  851. * Multiplies in place the current Vector2 coordinates by the passed ones.
  852. * Returns the updated Vector2.
  853. */
  854. Vector2.prototype.multiplyInPlace = function (otherVector) {
  855. this.x *= otherVector.x;
  856. this.y *= otherVector.y;
  857. return this;
  858. };
  859. /**
  860. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  861. */
  862. Vector2.prototype.multiply = function (otherVector) {
  863. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  864. };
  865. /**
  866. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  867. * Returns the Vector2.
  868. */
  869. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  870. result.x = this.x * otherVector.x;
  871. result.y = this.y * otherVector.y;
  872. return this;
  873. };
  874. /**
  875. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  876. */
  877. Vector2.prototype.multiplyByFloats = function (x, y) {
  878. return new Vector2(this.x * x, this.y * y);
  879. };
  880. /**
  881. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  882. */
  883. Vector2.prototype.divide = function (otherVector) {
  884. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  885. };
  886. /**
  887. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  888. * Returns the Vector2.
  889. */
  890. Vector2.prototype.divideToRef = function (otherVector, result) {
  891. result.x = this.x / otherVector.x;
  892. result.y = this.y / otherVector.y;
  893. return this;
  894. };
  895. /**
  896. * Returns a new Vector2 with current Vector2 negated coordinates.
  897. */
  898. Vector2.prototype.negate = function () {
  899. return new Vector2(-this.x, -this.y);
  900. };
  901. /**
  902. * Multiply the Vector2 coordinates by scale.
  903. * Returns the updated Vector2.
  904. */
  905. Vector2.prototype.scaleInPlace = function (scale) {
  906. this.x *= scale;
  907. this.y *= scale;
  908. return this;
  909. };
  910. /**
  911. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  912. */
  913. Vector2.prototype.scale = function (scale) {
  914. return new Vector2(this.x * scale, this.y * scale);
  915. };
  916. /**
  917. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  918. */
  919. Vector2.prototype.equals = function (otherVector) {
  920. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  921. };
  922. /**
  923. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  924. */
  925. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  926. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  927. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  928. };
  929. // Properties
  930. /**
  931. * Returns the vector length (float).
  932. */
  933. Vector2.prototype.length = function () {
  934. return Math.sqrt(this.x * this.x + this.y * this.y);
  935. };
  936. /**
  937. * Returns the vector squared length (float);
  938. */
  939. Vector2.prototype.lengthSquared = function () {
  940. return (this.x * this.x + this.y * this.y);
  941. };
  942. // Methods
  943. /**
  944. * Normalize the vector.
  945. * Returns the updated Vector2.
  946. */
  947. Vector2.prototype.normalize = function () {
  948. var len = this.length();
  949. if (len === 0)
  950. return this;
  951. var num = 1.0 / len;
  952. this.x *= num;
  953. this.y *= num;
  954. return this;
  955. };
  956. /**
  957. * Returns a new Vector2 copied from the Vector2.
  958. */
  959. Vector2.prototype.clone = function () {
  960. return new Vector2(this.x, this.y);
  961. };
  962. // Statics
  963. /**
  964. * Returns a new Vector2(0, 0)
  965. */
  966. Vector2.Zero = function () {
  967. return new Vector2(0, 0);
  968. };
  969. /**
  970. * Returns a new Vector2(1, 1)
  971. */
  972. Vector2.One = function () {
  973. return new Vector2(1, 1);
  974. };
  975. /**
  976. * Returns a new Vector2 set from the passed index element of the passed array.
  977. */
  978. Vector2.FromArray = function (array, offset) {
  979. if (offset === void 0) { offset = 0; }
  980. return new Vector2(array[offset], array[offset + 1]);
  981. };
  982. /**
  983. * Sets "result" from the passed index element of the passed array.
  984. */
  985. Vector2.FromArrayToRef = function (array, offset, result) {
  986. result.x = array[offset];
  987. result.y = array[offset + 1];
  988. };
  989. /**
  990. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  991. */
  992. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  993. var squared = amount * amount;
  994. var cubed = amount * squared;
  995. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  996. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  997. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  998. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  999. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1000. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1001. return new Vector2(x, y);
  1002. };
  1003. /**
  1004. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1005. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1006. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1007. */
  1008. Vector2.Clamp = function (value, min, max) {
  1009. var x = value.x;
  1010. x = (x > max.x) ? max.x : x;
  1011. x = (x < min.x) ? min.x : x;
  1012. var y = value.y;
  1013. y = (y > max.y) ? max.y : y;
  1014. y = (y < min.y) ? min.y : y;
  1015. return new Vector2(x, y);
  1016. };
  1017. /**
  1018. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1019. */
  1020. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1021. var squared = amount * amount;
  1022. var cubed = amount * squared;
  1023. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1024. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1025. var part3 = (cubed - (2.0 * squared)) + amount;
  1026. var part4 = cubed - squared;
  1027. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1028. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1029. return new Vector2(x, y);
  1030. };
  1031. /**
  1032. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1033. */
  1034. Vector2.Lerp = function (start, end, amount) {
  1035. var x = start.x + ((end.x - start.x) * amount);
  1036. var y = start.y + ((end.y - start.y) * amount);
  1037. return new Vector2(x, y);
  1038. };
  1039. /**
  1040. * Returns the dot product (float) of the vector "left" and the vector "right".
  1041. */
  1042. Vector2.Dot = function (left, right) {
  1043. return left.x * right.x + left.y * right.y;
  1044. };
  1045. /**
  1046. * Returns a new Vector2 equal to the normalized passed vector.
  1047. */
  1048. Vector2.Normalize = function (vector) {
  1049. var newVector = vector.clone();
  1050. newVector.normalize();
  1051. return newVector;
  1052. };
  1053. /**
  1054. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1055. */
  1056. Vector2.Minimize = function (left, right) {
  1057. var x = (left.x < right.x) ? left.x : right.x;
  1058. var y = (left.y < right.y) ? left.y : right.y;
  1059. return new Vector2(x, y);
  1060. };
  1061. /**
  1062. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1063. */
  1064. Vector2.Maximize = function (left, right) {
  1065. var x = (left.x > right.x) ? left.x : right.x;
  1066. var y = (left.y > right.y) ? left.y : right.y;
  1067. return new Vector2(x, y);
  1068. };
  1069. /**
  1070. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1071. */
  1072. Vector2.Transform = function (vector, transformation) {
  1073. var r = Vector2.Zero();
  1074. Vector2.TransformToRef(vector, transformation, r);
  1075. return r;
  1076. };
  1077. /**
  1078. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1079. */
  1080. Vector2.TransformToRef = function (vector, transformation, result) {
  1081. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1082. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1083. result.x = x;
  1084. result.y = y;
  1085. };
  1086. /**
  1087. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1088. */
  1089. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1090. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1091. var sign = a < 0 ? -1 : 1;
  1092. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1093. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1094. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1095. };
  1096. /**
  1097. * Returns the distance (float) between the vectors "value1" and "value2".
  1098. */
  1099. Vector2.Distance = function (value1, value2) {
  1100. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1101. };
  1102. /**
  1103. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1104. */
  1105. Vector2.DistanceSquared = function (value1, value2) {
  1106. var x = value1.x - value2.x;
  1107. var y = value1.y - value2.y;
  1108. return (x * x) + (y * y);
  1109. };
  1110. /**
  1111. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1112. */
  1113. Vector2.Center = function (value1, value2) {
  1114. var center = value1.add(value2);
  1115. center.scaleInPlace(0.5);
  1116. return center;
  1117. };
  1118. /**
  1119. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1120. */
  1121. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1122. var l2 = Vector2.DistanceSquared(segA, segB);
  1123. if (l2 === 0.0) {
  1124. return Vector2.Distance(p, segA);
  1125. }
  1126. var v = segB.subtract(segA);
  1127. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1128. var proj = segA.add(v.multiplyByFloats(t, t));
  1129. return Vector2.Distance(p, proj);
  1130. };
  1131. return Vector2;
  1132. }());
  1133. BABYLON.Vector2 = Vector2;
  1134. var Vector3 = (function () {
  1135. /**
  1136. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1137. * A Vector3 is the main object used in 3D geometry.
  1138. * It can represent etiher the coordinates of a point the space, either a direction.
  1139. */
  1140. function Vector3(x, y, z) {
  1141. this.x = x;
  1142. this.y = y;
  1143. this.z = z;
  1144. }
  1145. /**
  1146. * Returns a string with the Vector3 coordinates.
  1147. */
  1148. Vector3.prototype.toString = function () {
  1149. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1150. };
  1151. /**
  1152. * Returns the string "Vector3"
  1153. */
  1154. Vector3.prototype.getClassName = function () {
  1155. return "Vector3";
  1156. };
  1157. /**
  1158. * Returns the Vector hash code.
  1159. */
  1160. Vector3.prototype.getHashCode = function () {
  1161. var hash = this.x || 0;
  1162. hash = (hash * 397) ^ (this.y || 0);
  1163. hash = (hash * 397) ^ (this.z || 0);
  1164. return hash;
  1165. };
  1166. // Operators
  1167. /**
  1168. * Returns a new array with three elements : the coordinates the Vector3.
  1169. */
  1170. Vector3.prototype.asArray = function () {
  1171. var result = [];
  1172. this.toArray(result, 0);
  1173. return result;
  1174. };
  1175. /**
  1176. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1177. * Returns the Vector3.
  1178. */
  1179. Vector3.prototype.toArray = function (array, index) {
  1180. if (index === void 0) { index = 0; }
  1181. array[index] = this.x;
  1182. array[index + 1] = this.y;
  1183. array[index + 2] = this.z;
  1184. return this;
  1185. };
  1186. /**
  1187. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1188. */
  1189. Vector3.prototype.toQuaternion = function () {
  1190. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1191. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1192. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1193. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1194. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1195. var cosy = Math.cos(this.y * 0.5);
  1196. var siny = Math.sin(this.y * 0.5);
  1197. result.x = coszMinusx * siny;
  1198. result.y = -sinzMinusx * siny;
  1199. result.z = sinxPlusz * cosy;
  1200. result.w = cosxPlusz * cosy;
  1201. return result;
  1202. };
  1203. /**
  1204. * Adds the passed vector to the current Vector3.
  1205. * Returns the updated Vector3.
  1206. */
  1207. Vector3.prototype.addInPlace = function (otherVector) {
  1208. this.x += otherVector.x;
  1209. this.y += otherVector.y;
  1210. this.z += otherVector.z;
  1211. return this;
  1212. };
  1213. /**
  1214. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1215. */
  1216. Vector3.prototype.add = function (otherVector) {
  1217. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1218. };
  1219. /**
  1220. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1221. * Returns the current Vector3.
  1222. */
  1223. Vector3.prototype.addToRef = function (otherVector, result) {
  1224. result.x = this.x + otherVector.x;
  1225. result.y = this.y + otherVector.y;
  1226. result.z = this.z + otherVector.z;
  1227. return this;
  1228. };
  1229. /**
  1230. * Subtract the passed vector from the current Vector3.
  1231. * Returns the updated Vector3.
  1232. */
  1233. Vector3.prototype.subtractInPlace = function (otherVector) {
  1234. this.x -= otherVector.x;
  1235. this.y -= otherVector.y;
  1236. this.z -= otherVector.z;
  1237. return this;
  1238. };
  1239. /**
  1240. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1241. */
  1242. Vector3.prototype.subtract = function (otherVector) {
  1243. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1244. };
  1245. /**
  1246. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1247. * Returns the current Vector3.
  1248. */
  1249. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1250. result.x = this.x - otherVector.x;
  1251. result.y = this.y - otherVector.y;
  1252. result.z = this.z - otherVector.z;
  1253. return this;
  1254. };
  1255. /**
  1256. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1257. */
  1258. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1259. return new Vector3(this.x - x, this.y - y, this.z - z);
  1260. };
  1261. /**
  1262. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1263. * Returns the current Vector3.
  1264. */
  1265. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1266. result.x = this.x - x;
  1267. result.y = this.y - y;
  1268. result.z = this.z - z;
  1269. return this;
  1270. };
  1271. /**
  1272. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1273. */
  1274. Vector3.prototype.negate = function () {
  1275. return new Vector3(-this.x, -this.y, -this.z);
  1276. };
  1277. /**
  1278. * Multiplies the Vector3 coordinates by the float "scale".
  1279. * Returns the updated Vector3.
  1280. */
  1281. Vector3.prototype.scaleInPlace = function (scale) {
  1282. this.x *= scale;
  1283. this.y *= scale;
  1284. this.z *= scale;
  1285. return this;
  1286. };
  1287. /**
  1288. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1289. */
  1290. Vector3.prototype.scale = function (scale) {
  1291. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1292. };
  1293. /**
  1294. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1295. * Returns the current Vector3.
  1296. */
  1297. Vector3.prototype.scaleToRef = function (scale, result) {
  1298. result.x = this.x * scale;
  1299. result.y = this.y * scale;
  1300. result.z = this.z * scale;
  1301. return this;
  1302. };
  1303. /**
  1304. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1305. */
  1306. Vector3.prototype.equals = function (otherVector) {
  1307. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1308. };
  1309. /**
  1310. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1311. */
  1312. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1313. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1314. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1315. };
  1316. /**
  1317. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1318. */
  1319. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1320. return this.x === x && this.y === y && this.z === z;
  1321. };
  1322. /**
  1323. * Muliplies the current Vector3 coordinates by the passed ones.
  1324. * Returns the updated Vector3.
  1325. */
  1326. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1327. this.x *= otherVector.x;
  1328. this.y *= otherVector.y;
  1329. this.z *= otherVector.z;
  1330. return this;
  1331. };
  1332. /**
  1333. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1334. */
  1335. Vector3.prototype.multiply = function (otherVector) {
  1336. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1337. };
  1338. /**
  1339. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1340. * Returns the current Vector3.
  1341. */
  1342. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1343. result.x = this.x * otherVector.x;
  1344. result.y = this.y * otherVector.y;
  1345. result.z = this.z * otherVector.z;
  1346. return this;
  1347. };
  1348. /**
  1349. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1350. */
  1351. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1352. return new Vector3(this.x * x, this.y * y, this.z * z);
  1353. };
  1354. /**
  1355. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1356. */
  1357. Vector3.prototype.divide = function (otherVector) {
  1358. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1359. };
  1360. /**
  1361. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1362. * Returns the current Vector3.
  1363. */
  1364. Vector3.prototype.divideToRef = function (otherVector, result) {
  1365. result.x = this.x / otherVector.x;
  1366. result.y = this.y / otherVector.y;
  1367. result.z = this.z / otherVector.z;
  1368. return this;
  1369. };
  1370. /**
  1371. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1372. * Returns the updated Vector3.
  1373. */
  1374. Vector3.prototype.MinimizeInPlace = function (other) {
  1375. if (other.x < this.x)
  1376. this.x = other.x;
  1377. if (other.y < this.y)
  1378. this.y = other.y;
  1379. if (other.z < this.z)
  1380. this.z = other.z;
  1381. return this;
  1382. };
  1383. /**
  1384. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1385. * Returns the updated Vector3.
  1386. */
  1387. Vector3.prototype.MaximizeInPlace = function (other) {
  1388. if (other.x > this.x)
  1389. this.x = other.x;
  1390. if (other.y > this.y)
  1391. this.y = other.y;
  1392. if (other.z > this.z)
  1393. this.z = other.z;
  1394. return this;
  1395. };
  1396. // Properties
  1397. /**
  1398. * Returns the length of the Vector3 (float).
  1399. */
  1400. Vector3.prototype.length = function () {
  1401. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1402. };
  1403. /**
  1404. * Returns the squared length of the Vector3 (float).
  1405. */
  1406. Vector3.prototype.lengthSquared = function () {
  1407. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1408. };
  1409. // Methods
  1410. /**
  1411. * Normalize the current Vector3.
  1412. * Returns the updated Vector3.
  1413. */
  1414. Vector3.prototype.normalize = function () {
  1415. var len = this.length();
  1416. if (len === 0 || len === 1.0)
  1417. return this;
  1418. var num = 1.0 / len;
  1419. this.x *= num;
  1420. this.y *= num;
  1421. this.z *= num;
  1422. return this;
  1423. };
  1424. /**
  1425. * Returns a new Vector3 copied from the current Vector3.
  1426. */
  1427. Vector3.prototype.clone = function () {
  1428. return new Vector3(this.x, this.y, this.z);
  1429. };
  1430. /**
  1431. * Copies the passed vector coordinates to the current Vector3 ones.
  1432. * Returns the updated Vector3.
  1433. */
  1434. Vector3.prototype.copyFrom = function (source) {
  1435. this.x = source.x;
  1436. this.y = source.y;
  1437. this.z = source.z;
  1438. return this;
  1439. };
  1440. /**
  1441. * Copies the passed floats to the current Vector3 coordinates.
  1442. * Returns the updated Vector3.
  1443. */
  1444. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1445. this.x = x;
  1446. this.y = y;
  1447. this.z = z;
  1448. return this;
  1449. };
  1450. /**
  1451. * Copies the passed floats to the current Vector3 coordinates.
  1452. * Returns the updated Vector3.
  1453. */
  1454. Vector3.prototype.set = function (x, y, z) {
  1455. return this.copyFromFloats(x, y, z);
  1456. };
  1457. // Statics
  1458. /**
  1459. *
  1460. */
  1461. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1462. var d0 = Vector3.Dot(vector0, axis) - size;
  1463. var d1 = Vector3.Dot(vector1, axis) - size;
  1464. var s = d0 / (d0 - d1);
  1465. return s;
  1466. };
  1467. /**
  1468. * Returns a new Vector3 set from the index "offset" of the passed array.
  1469. */
  1470. Vector3.FromArray = function (array, offset) {
  1471. if (!offset) {
  1472. offset = 0;
  1473. }
  1474. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1475. };
  1476. /**
  1477. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1478. * This function is deprecated. Use FromArray instead.
  1479. */
  1480. Vector3.FromFloatArray = function (array, offset) {
  1481. return Vector3.FromArray(array, offset);
  1482. };
  1483. /**
  1484. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1485. */
  1486. Vector3.FromArrayToRef = function (array, offset, result) {
  1487. result.x = array[offset];
  1488. result.y = array[offset + 1];
  1489. result.z = array[offset + 2];
  1490. };
  1491. /**
  1492. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1493. * This function is deprecated. Use FromArrayToRef instead.
  1494. */
  1495. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1496. return Vector3.FromArrayToRef(array, offset, result);
  1497. };
  1498. /**
  1499. * Sets the passed vector "result" with the passed floats.
  1500. */
  1501. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1502. result.x = x;
  1503. result.y = y;
  1504. result.z = z;
  1505. };
  1506. /**
  1507. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1508. */
  1509. Vector3.Zero = function () {
  1510. return new Vector3(0.0, 0.0, 0.0);
  1511. };
  1512. /**
  1513. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1514. */
  1515. Vector3.One = function () {
  1516. return new Vector3(1.0, 1.0, 1.0);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1520. */
  1521. Vector3.Up = function () {
  1522. return new Vector3(0.0, 1.0, 0.0);
  1523. };
  1524. /**
  1525. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1526. */
  1527. Vector3.Forward = function () {
  1528. return new Vector3(0.0, 0.0, 1.0);
  1529. };
  1530. /**
  1531. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1532. */
  1533. Vector3.Right = function () {
  1534. return new Vector3(1.0, 0.0, 0.0);
  1535. };
  1536. /**
  1537. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1538. */
  1539. Vector3.Left = function () {
  1540. return new Vector3(-1.0, 0.0, 0.0);
  1541. };
  1542. /**
  1543. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1544. * This method computes tranformed coordinates only, not transformed direction vectors.
  1545. */
  1546. Vector3.TransformCoordinates = function (vector, transformation) {
  1547. var result = Vector3.Zero();
  1548. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1549. return result;
  1550. };
  1551. /**
  1552. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1553. * This method computes tranformed coordinates only, not transformed direction vectors.
  1554. */
  1555. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1556. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1557. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1558. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1559. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1560. result.x = x / w;
  1561. result.y = y / w;
  1562. result.z = z / w;
  1563. };
  1564. /**
  1565. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1566. * This method computes tranformed coordinates only, not transformed direction vectors.
  1567. */
  1568. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1569. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1570. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1571. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1572. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1573. result.x = rx / rw;
  1574. result.y = ry / rw;
  1575. result.z = rz / rw;
  1576. };
  1577. /**
  1578. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1579. * This methods computes transformed normalized direction vectors only.
  1580. */
  1581. Vector3.TransformNormal = function (vector, transformation) {
  1582. var result = Vector3.Zero();
  1583. Vector3.TransformNormalToRef(vector, transformation, result);
  1584. return result;
  1585. };
  1586. /**
  1587. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1588. * This methods computes transformed normalized direction vectors only.
  1589. */
  1590. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1591. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1592. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1593. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1594. result.x = x;
  1595. result.y = y;
  1596. result.z = z;
  1597. };
  1598. /**
  1599. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1600. * This methods computes transformed normalized direction vectors only.
  1601. */
  1602. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1603. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1604. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1605. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1606. };
  1607. /**
  1608. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1609. */
  1610. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1611. var squared = amount * amount;
  1612. var cubed = amount * squared;
  1613. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1614. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1615. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1616. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1617. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1618. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1619. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1620. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1621. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1622. return new Vector3(x, y, z);
  1623. };
  1624. /**
  1625. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1626. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1627. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1628. */
  1629. Vector3.Clamp = function (value, min, max) {
  1630. var x = value.x;
  1631. x = (x > max.x) ? max.x : x;
  1632. x = (x < min.x) ? min.x : x;
  1633. var y = value.y;
  1634. y = (y > max.y) ? max.y : y;
  1635. y = (y < min.y) ? min.y : y;
  1636. var z = value.z;
  1637. z = (z > max.z) ? max.z : z;
  1638. z = (z < min.z) ? min.z : z;
  1639. return new Vector3(x, y, z);
  1640. };
  1641. /**
  1642. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1643. */
  1644. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1645. var squared = amount * amount;
  1646. var cubed = amount * squared;
  1647. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1648. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1649. var part3 = (cubed - (2.0 * squared)) + amount;
  1650. var part4 = cubed - squared;
  1651. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1652. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1653. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1654. return new Vector3(x, y, z);
  1655. };
  1656. /**
  1657. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1658. */
  1659. Vector3.Lerp = function (start, end, amount) {
  1660. var result = new Vector3(0, 0, 0);
  1661. Vector3.LerpToRef(start, end, amount, result);
  1662. return result;
  1663. };
  1664. /**
  1665. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1666. */
  1667. Vector3.LerpToRef = function (start, end, amount, result) {
  1668. result.x = start.x + ((end.x - start.x) * amount);
  1669. result.y = start.y + ((end.y - start.y) * amount);
  1670. result.z = start.z + ((end.z - start.z) * amount);
  1671. };
  1672. /**
  1673. * Returns the dot product (float) between the vectors "left" and "right".
  1674. */
  1675. Vector3.Dot = function (left, right) {
  1676. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1677. };
  1678. /**
  1679. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1680. * The cross product is then orthogonal to both "left" and "right".
  1681. */
  1682. Vector3.Cross = function (left, right) {
  1683. var result = Vector3.Zero();
  1684. Vector3.CrossToRef(left, right, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the cross product of "left" and "right".
  1689. * The cross product is then orthogonal to both "left" and "right".
  1690. */
  1691. Vector3.CrossToRef = function (left, right, result) {
  1692. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1693. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1694. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1695. result.copyFrom(MathTmp.Vector3[0]);
  1696. };
  1697. /**
  1698. * Returns a new Vector3 as the normalization of the passed vector.
  1699. */
  1700. Vector3.Normalize = function (vector) {
  1701. var result = Vector3.Zero();
  1702. Vector3.NormalizeToRef(vector, result);
  1703. return result;
  1704. };
  1705. /**
  1706. * Sets the passed vector "result" with the normalization of the passed first vector.
  1707. */
  1708. Vector3.NormalizeToRef = function (vector, result) {
  1709. result.copyFrom(vector);
  1710. result.normalize();
  1711. };
  1712. Vector3.Project = function (vector, world, transform, viewport) {
  1713. var cw = viewport.width;
  1714. var ch = viewport.height;
  1715. var cx = viewport.x;
  1716. var cy = viewport.y;
  1717. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1718. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1719. var matrix = MathTmp.Matrix[0];
  1720. world.multiplyToRef(transform, matrix);
  1721. matrix.multiplyToRef(viewportMatrix, matrix);
  1722. return Vector3.TransformCoordinates(vector, matrix);
  1723. };
  1724. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1725. var matrix = MathTmp.Matrix[0];
  1726. world.multiplyToRef(transform, matrix);
  1727. matrix.invert();
  1728. source.x = source.x / viewportWidth * 2 - 1;
  1729. source.y = -(source.y / viewportHeight * 2 - 1);
  1730. var vector = Vector3.TransformCoordinates(source, matrix);
  1731. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1732. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1733. vector = vector.scale(1.0 / num);
  1734. }
  1735. return vector;
  1736. };
  1737. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1738. var matrix = MathTmp.Matrix[0];
  1739. world.multiplyToRef(view, matrix);
  1740. matrix.multiplyToRef(projection, matrix);
  1741. matrix.invert();
  1742. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1743. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1744. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1745. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1746. vector = vector.scale(1.0 / num);
  1747. }
  1748. return vector;
  1749. };
  1750. Vector3.Minimize = function (left, right) {
  1751. var min = left.clone();
  1752. min.MinimizeInPlace(right);
  1753. return min;
  1754. };
  1755. Vector3.Maximize = function (left, right) {
  1756. var max = left.clone();
  1757. max.MaximizeInPlace(right);
  1758. return max;
  1759. };
  1760. /**
  1761. * Returns the distance (float) between the vectors "value1" and "value2".
  1762. */
  1763. Vector3.Distance = function (value1, value2) {
  1764. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1765. };
  1766. /**
  1767. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1768. */
  1769. Vector3.DistanceSquared = function (value1, value2) {
  1770. var x = value1.x - value2.x;
  1771. var y = value1.y - value2.y;
  1772. var z = value1.z - value2.z;
  1773. return (x * x) + (y * y) + (z * z);
  1774. };
  1775. /**
  1776. * Returns a new Vector3 located at the center between "value1" and "value2".
  1777. */
  1778. Vector3.Center = function (value1, value2) {
  1779. var center = value1.add(value2);
  1780. center.scaleInPlace(0.5);
  1781. return center;
  1782. };
  1783. /**
  1784. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1785. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1786. * to something in order to rotate it from its local system to the given target system.
  1787. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1788. * Returns a new Vector3.
  1789. */
  1790. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1791. var rotation = Vector3.Zero();
  1792. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1793. return rotation;
  1794. };
  1795. /**
  1796. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1797. */
  1798. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1799. var quat = MathTmp.Quaternion[0];
  1800. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1801. quat.toEulerAnglesToRef(ref);
  1802. };
  1803. return Vector3;
  1804. }());
  1805. BABYLON.Vector3 = Vector3;
  1806. //Vector4 class created for EulerAngle class conversion to Quaternion
  1807. var Vector4 = (function () {
  1808. /**
  1809. * Creates a Vector4 object from the passed floats.
  1810. */
  1811. function Vector4(x, y, z, w) {
  1812. this.x = x;
  1813. this.y = y;
  1814. this.z = z;
  1815. this.w = w;
  1816. }
  1817. /**
  1818. * Returns the string with the Vector4 coordinates.
  1819. */
  1820. Vector4.prototype.toString = function () {
  1821. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1822. };
  1823. /**
  1824. * Returns the string "Vector4".
  1825. */
  1826. Vector4.prototype.getClassName = function () {
  1827. return "Vector4";
  1828. };
  1829. /**
  1830. * Returns the Vector4 hash code.
  1831. */
  1832. Vector4.prototype.getHashCode = function () {
  1833. var hash = this.x || 0;
  1834. hash = (hash * 397) ^ (this.y || 0);
  1835. hash = (hash * 397) ^ (this.z || 0);
  1836. hash = (hash * 397) ^ (this.w || 0);
  1837. return hash;
  1838. };
  1839. // Operators
  1840. /**
  1841. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1842. */
  1843. Vector4.prototype.asArray = function () {
  1844. var result = [];
  1845. this.toArray(result, 0);
  1846. return result;
  1847. };
  1848. /**
  1849. * Populates the passed array from the passed index with the Vector4 coordinates.
  1850. * Returns the Vector4.
  1851. */
  1852. Vector4.prototype.toArray = function (array, index) {
  1853. if (index === undefined) {
  1854. index = 0;
  1855. }
  1856. array[index] = this.x;
  1857. array[index + 1] = this.y;
  1858. array[index + 2] = this.z;
  1859. array[index + 3] = this.w;
  1860. return this;
  1861. };
  1862. /**
  1863. * Adds the passed vector to the current Vector4.
  1864. * Returns the updated Vector4.
  1865. */
  1866. Vector4.prototype.addInPlace = function (otherVector) {
  1867. this.x += otherVector.x;
  1868. this.y += otherVector.y;
  1869. this.z += otherVector.z;
  1870. this.w += otherVector.w;
  1871. return this;
  1872. };
  1873. /**
  1874. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1875. */
  1876. Vector4.prototype.add = function (otherVector) {
  1877. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1878. };
  1879. /**
  1880. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1881. * Returns the current Vector4.
  1882. */
  1883. Vector4.prototype.addToRef = function (otherVector, result) {
  1884. result.x = this.x + otherVector.x;
  1885. result.y = this.y + otherVector.y;
  1886. result.z = this.z + otherVector.z;
  1887. result.w = this.w + otherVector.w;
  1888. return this;
  1889. };
  1890. /**
  1891. * Subtract in place the passed vector from the current Vector4.
  1892. * Returns the updated Vector4.
  1893. */
  1894. Vector4.prototype.subtractInPlace = function (otherVector) {
  1895. this.x -= otherVector.x;
  1896. this.y -= otherVector.y;
  1897. this.z -= otherVector.z;
  1898. this.w -= otherVector.w;
  1899. return this;
  1900. };
  1901. /**
  1902. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1903. */
  1904. Vector4.prototype.subtract = function (otherVector) {
  1905. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1906. };
  1907. /**
  1908. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1909. * Returns the current Vector4.
  1910. */
  1911. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1912. result.x = this.x - otherVector.x;
  1913. result.y = this.y - otherVector.y;
  1914. result.z = this.z - otherVector.z;
  1915. result.w = this.w - otherVector.w;
  1916. return this;
  1917. };
  1918. /**
  1919. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1920. */
  1921. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1922. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1923. };
  1924. /**
  1925. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1926. * Returns the current Vector4.
  1927. */
  1928. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1929. result.x = this.x - x;
  1930. result.y = this.y - y;
  1931. result.z = this.z - z;
  1932. result.w = this.w - w;
  1933. return this;
  1934. };
  1935. /**
  1936. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1937. */
  1938. Vector4.prototype.negate = function () {
  1939. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1940. };
  1941. /**
  1942. * Multiplies the current Vector4 coordinates by scale (float).
  1943. * Returns the updated Vector4.
  1944. */
  1945. Vector4.prototype.scaleInPlace = function (scale) {
  1946. this.x *= scale;
  1947. this.y *= scale;
  1948. this.z *= scale;
  1949. this.w *= scale;
  1950. return this;
  1951. };
  1952. /**
  1953. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1954. */
  1955. Vector4.prototype.scale = function (scale) {
  1956. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1957. };
  1958. /**
  1959. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1960. * Returns the current Vector4.
  1961. */
  1962. Vector4.prototype.scaleToRef = function (scale, result) {
  1963. result.x = this.x * scale;
  1964. result.y = this.y * scale;
  1965. result.z = this.z * scale;
  1966. result.w = this.w * scale;
  1967. return this;
  1968. };
  1969. /**
  1970. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1971. */
  1972. Vector4.prototype.equals = function (otherVector) {
  1973. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1974. };
  1975. /**
  1976. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1977. */
  1978. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1979. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1980. return otherVector
  1981. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1982. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1983. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1984. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1985. };
  1986. /**
  1987. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1988. */
  1989. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1990. return this.x === x && this.y === y && this.z === z && this.w === w;
  1991. };
  1992. /**
  1993. * Multiplies in place the current Vector4 by the passed one.
  1994. * Returns the updated Vector4.
  1995. */
  1996. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1997. this.x *= otherVector.x;
  1998. this.y *= otherVector.y;
  1999. this.z *= otherVector.z;
  2000. this.w *= otherVector.w;
  2001. return this;
  2002. };
  2003. /**
  2004. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2005. */
  2006. Vector4.prototype.multiply = function (otherVector) {
  2007. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2011. * Returns the current Vector4.
  2012. */
  2013. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2014. result.x = this.x * otherVector.x;
  2015. result.y = this.y * otherVector.y;
  2016. result.z = this.z * otherVector.z;
  2017. result.w = this.w * otherVector.w;
  2018. return this;
  2019. };
  2020. /**
  2021. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2022. */
  2023. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2024. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2025. };
  2026. /**
  2027. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2028. */
  2029. Vector4.prototype.divide = function (otherVector) {
  2030. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2031. };
  2032. /**
  2033. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2034. * Returns the current Vector4.
  2035. */
  2036. Vector4.prototype.divideToRef = function (otherVector, result) {
  2037. result.x = this.x / otherVector.x;
  2038. result.y = this.y / otherVector.y;
  2039. result.z = this.z / otherVector.z;
  2040. result.w = this.w / otherVector.w;
  2041. return this;
  2042. };
  2043. /**
  2044. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2045. */
  2046. Vector4.prototype.MinimizeInPlace = function (other) {
  2047. if (other.x < this.x)
  2048. this.x = other.x;
  2049. if (other.y < this.y)
  2050. this.y = other.y;
  2051. if (other.z < this.z)
  2052. this.z = other.z;
  2053. if (other.w < this.w)
  2054. this.w = other.w;
  2055. return this;
  2056. };
  2057. /**
  2058. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2059. */
  2060. Vector4.prototype.MaximizeInPlace = function (other) {
  2061. if (other.x > this.x)
  2062. this.x = other.x;
  2063. if (other.y > this.y)
  2064. this.y = other.y;
  2065. if (other.z > this.z)
  2066. this.z = other.z;
  2067. if (other.w > this.w)
  2068. this.w = other.w;
  2069. return this;
  2070. };
  2071. // Properties
  2072. /**
  2073. * Returns the Vector4 length (float).
  2074. */
  2075. Vector4.prototype.length = function () {
  2076. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2077. };
  2078. /**
  2079. * Returns the Vector4 squared length (float).
  2080. */
  2081. Vector4.prototype.lengthSquared = function () {
  2082. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2083. };
  2084. // Methods
  2085. /**
  2086. * Normalizes in place the Vector4.
  2087. * Returns the updated Vector4.
  2088. */
  2089. Vector4.prototype.normalize = function () {
  2090. var len = this.length();
  2091. if (len === 0)
  2092. return this;
  2093. var num = 1.0 / len;
  2094. this.x *= num;
  2095. this.y *= num;
  2096. this.z *= num;
  2097. this.w *= num;
  2098. return this;
  2099. };
  2100. /**
  2101. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2102. */
  2103. Vector4.prototype.toVector3 = function () {
  2104. return new Vector3(this.x, this.y, this.z);
  2105. };
  2106. /**
  2107. * Returns a new Vector4 copied from the current one.
  2108. */
  2109. Vector4.prototype.clone = function () {
  2110. return new Vector4(this.x, this.y, this.z, this.w);
  2111. };
  2112. /**
  2113. * Updates the current Vector4 with the passed one coordinates.
  2114. * Returns the updated Vector4.
  2115. */
  2116. Vector4.prototype.copyFrom = function (source) {
  2117. this.x = source.x;
  2118. this.y = source.y;
  2119. this.z = source.z;
  2120. this.w = source.w;
  2121. return this;
  2122. };
  2123. /**
  2124. * Updates the current Vector4 coordinates with the passed floats.
  2125. * Returns the updated Vector4.
  2126. */
  2127. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2128. this.x = x;
  2129. this.y = y;
  2130. this.z = z;
  2131. this.w = w;
  2132. return this;
  2133. };
  2134. /**
  2135. * Updates the current Vector4 coordinates with the passed floats.
  2136. * Returns the updated Vector4.
  2137. */
  2138. Vector4.prototype.set = function (x, y, z, w) {
  2139. return this.copyFromFloats(x, y, z, w);
  2140. };
  2141. // Statics
  2142. /**
  2143. * Returns a new Vector4 set from the starting index of the passed array.
  2144. */
  2145. Vector4.FromArray = function (array, offset) {
  2146. if (!offset) {
  2147. offset = 0;
  2148. }
  2149. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2150. };
  2151. /**
  2152. * Updates the passed vector "result" from the starting index of the passed array.
  2153. */
  2154. Vector4.FromArrayToRef = function (array, offset, result) {
  2155. result.x = array[offset];
  2156. result.y = array[offset + 1];
  2157. result.z = array[offset + 2];
  2158. result.w = array[offset + 3];
  2159. };
  2160. /**
  2161. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2162. */
  2163. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2164. Vector4.FromArrayToRef(array, offset, result);
  2165. };
  2166. /**
  2167. * Updates the passed vector "result" coordinates from the passed floats.
  2168. */
  2169. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2170. result.x = x;
  2171. result.y = y;
  2172. result.z = z;
  2173. result.w = w;
  2174. };
  2175. /**
  2176. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2177. */
  2178. Vector4.Zero = function () {
  2179. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2180. };
  2181. /**
  2182. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2183. */
  2184. Vector4.One = function () {
  2185. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2186. };
  2187. /**
  2188. * Returns a new normalized Vector4 from the passed one.
  2189. */
  2190. Vector4.Normalize = function (vector) {
  2191. var result = Vector4.Zero();
  2192. Vector4.NormalizeToRef(vector, result);
  2193. return result;
  2194. };
  2195. /**
  2196. * Updates the passed vector "result" from the normalization of the passed one.
  2197. */
  2198. Vector4.NormalizeToRef = function (vector, result) {
  2199. result.copyFrom(vector);
  2200. result.normalize();
  2201. };
  2202. Vector4.Minimize = function (left, right) {
  2203. var min = left.clone();
  2204. min.MinimizeInPlace(right);
  2205. return min;
  2206. };
  2207. Vector4.Maximize = function (left, right) {
  2208. var max = left.clone();
  2209. max.MaximizeInPlace(right);
  2210. return max;
  2211. };
  2212. /**
  2213. * Returns the distance (float) between the vectors "value1" and "value2".
  2214. */
  2215. Vector4.Distance = function (value1, value2) {
  2216. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2217. };
  2218. /**
  2219. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2220. */
  2221. Vector4.DistanceSquared = function (value1, value2) {
  2222. var x = value1.x - value2.x;
  2223. var y = value1.y - value2.y;
  2224. var z = value1.z - value2.z;
  2225. var w = value1.w - value2.w;
  2226. return (x * x) + (y * y) + (z * z) + (w * w);
  2227. };
  2228. /**
  2229. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2230. */
  2231. Vector4.Center = function (value1, value2) {
  2232. var center = value1.add(value2);
  2233. center.scaleInPlace(0.5);
  2234. return center;
  2235. };
  2236. /**
  2237. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2238. * This methods computes transformed normalized direction vectors only.
  2239. */
  2240. Vector4.TransformNormal = function (vector, transformation) {
  2241. var result = Vector4.Zero();
  2242. Vector4.TransformNormalToRef(vector, transformation, result);
  2243. return result;
  2244. };
  2245. /**
  2246. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2247. * This methods computes transformed normalized direction vectors only.
  2248. */
  2249. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2250. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2251. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2252. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2253. result.x = x;
  2254. result.y = y;
  2255. result.z = z;
  2256. result.w = vector.w;
  2257. };
  2258. /**
  2259. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2260. * This methods computes transformed normalized direction vectors only.
  2261. */
  2262. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2263. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2264. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2265. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2266. result.w = w;
  2267. };
  2268. return Vector4;
  2269. }());
  2270. BABYLON.Vector4 = Vector4;
  2271. var Size = (function () {
  2272. /**
  2273. * Creates a Size object from the passed width and height (floats).
  2274. */
  2275. function Size(width, height) {
  2276. this.width = width;
  2277. this.height = height;
  2278. }
  2279. // Returns a string with the Size width and height.
  2280. Size.prototype.toString = function () {
  2281. return "{W: " + this.width + ", H: " + this.height + "}";
  2282. };
  2283. /**
  2284. * Returns the string "Size"
  2285. */
  2286. Size.prototype.getClassName = function () {
  2287. return "Size";
  2288. };
  2289. /**
  2290. * Returns the Size hash code.
  2291. */
  2292. Size.prototype.getHashCode = function () {
  2293. var hash = this.width || 0;
  2294. hash = (hash * 397) ^ (this.height || 0);
  2295. return hash;
  2296. };
  2297. /**
  2298. * Updates the current size from the passed one.
  2299. * Returns the updated Size.
  2300. */
  2301. Size.prototype.copyFrom = function (src) {
  2302. this.width = src.width;
  2303. this.height = src.height;
  2304. };
  2305. /**
  2306. * Updates in place the current Size from the passed floats.
  2307. * Returns the updated Size.
  2308. */
  2309. Size.prototype.copyFromFloats = function (width, height) {
  2310. this.width = width;
  2311. this.height = height;
  2312. return this;
  2313. };
  2314. /**
  2315. * Updates in place the current Size from the passed floats.
  2316. * Returns the updated Size.
  2317. */
  2318. Size.prototype.set = function (width, height) {
  2319. return this.copyFromFloats(width, height);
  2320. };
  2321. /**
  2322. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2323. */
  2324. Size.prototype.multiplyByFloats = function (w, h) {
  2325. return new Size(this.width * w, this.height * h);
  2326. };
  2327. /**
  2328. * Returns a new Size copied from the passed one.
  2329. */
  2330. Size.prototype.clone = function () {
  2331. return new Size(this.width, this.height);
  2332. };
  2333. /**
  2334. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2335. */
  2336. Size.prototype.equals = function (other) {
  2337. if (!other) {
  2338. return false;
  2339. }
  2340. return (this.width === other.width) && (this.height === other.height);
  2341. };
  2342. Object.defineProperty(Size.prototype, "surface", {
  2343. /**
  2344. * Returns the surface of the Size : width * height (float).
  2345. */
  2346. get: function () {
  2347. return this.width * this.height;
  2348. },
  2349. enumerable: true,
  2350. configurable: true
  2351. });
  2352. /**
  2353. * Returns a new Size set to (0.0, 0.0)
  2354. */
  2355. Size.Zero = function () {
  2356. return new Size(0.0, 0.0);
  2357. };
  2358. /**
  2359. * Returns a new Size set as the addition result of the current Size and the passed one.
  2360. */
  2361. Size.prototype.add = function (otherSize) {
  2362. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2363. return r;
  2364. };
  2365. /**
  2366. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2367. */
  2368. Size.prototype.subtract = function (otherSize) {
  2369. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2370. return r;
  2371. };
  2372. /**
  2373. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2374. */
  2375. Size.Lerp = function (start, end, amount) {
  2376. var w = start.width + ((end.width - start.width) * amount);
  2377. var h = start.height + ((end.height - start.height) * amount);
  2378. return new Size(w, h);
  2379. };
  2380. return Size;
  2381. }());
  2382. BABYLON.Size = Size;
  2383. var Quaternion = (function () {
  2384. /**
  2385. * Creates a new Quaternion from the passed floats.
  2386. */
  2387. function Quaternion(x, y, z, w) {
  2388. if (x === void 0) { x = 0.0; }
  2389. if (y === void 0) { y = 0.0; }
  2390. if (z === void 0) { z = 0.0; }
  2391. if (w === void 0) { w = 1.0; }
  2392. this.x = x;
  2393. this.y = y;
  2394. this.z = z;
  2395. this.w = w;
  2396. }
  2397. /**
  2398. * Returns a string with the Quaternion coordinates.
  2399. */
  2400. Quaternion.prototype.toString = function () {
  2401. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2402. };
  2403. /**
  2404. * Returns the string "Quaternion".
  2405. */
  2406. Quaternion.prototype.getClassName = function () {
  2407. return "Quaternion";
  2408. };
  2409. /**
  2410. * Returns the Quaternion hash code.
  2411. */
  2412. Quaternion.prototype.getHashCode = function () {
  2413. var hash = this.x || 0;
  2414. hash = (hash * 397) ^ (this.y || 0);
  2415. hash = (hash * 397) ^ (this.z || 0);
  2416. hash = (hash * 397) ^ (this.w || 0);
  2417. return hash;
  2418. };
  2419. /**
  2420. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2421. */
  2422. Quaternion.prototype.asArray = function () {
  2423. return [this.x, this.y, this.z, this.w];
  2424. };
  2425. /**
  2426. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2427. */
  2428. Quaternion.prototype.equals = function (otherQuaternion) {
  2429. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2430. };
  2431. /**
  2432. * Returns a new Quaternion copied from the current one.
  2433. */
  2434. Quaternion.prototype.clone = function () {
  2435. return new Quaternion(this.x, this.y, this.z, this.w);
  2436. };
  2437. /**
  2438. * Updates the current Quaternion from the passed one coordinates.
  2439. * Returns the updated Quaterion.
  2440. */
  2441. Quaternion.prototype.copyFrom = function (other) {
  2442. this.x = other.x;
  2443. this.y = other.y;
  2444. this.z = other.z;
  2445. this.w = other.w;
  2446. return this;
  2447. };
  2448. /**
  2449. * Updates the current Quaternion from the passed float coordinates.
  2450. * Returns the updated Quaterion.
  2451. */
  2452. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2453. this.x = x;
  2454. this.y = y;
  2455. this.z = z;
  2456. this.w = w;
  2457. return this;
  2458. };
  2459. /**
  2460. * Updates the current Quaternion from the passed float coordinates.
  2461. * Returns the updated Quaterion.
  2462. */
  2463. Quaternion.prototype.set = function (x, y, z, w) {
  2464. return this.copyFromFloats(x, y, z, w);
  2465. };
  2466. /**
  2467. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2468. */
  2469. Quaternion.prototype.add = function (other) {
  2470. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2471. };
  2472. /**
  2473. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2474. */
  2475. Quaternion.prototype.subtract = function (other) {
  2476. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2477. };
  2478. /**
  2479. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2480. */
  2481. Quaternion.prototype.scale = function (value) {
  2482. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2483. };
  2484. /**
  2485. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2486. */
  2487. Quaternion.prototype.multiply = function (q1) {
  2488. var result = new Quaternion(0, 0, 0, 1.0);
  2489. this.multiplyToRef(q1, result);
  2490. return result;
  2491. };
  2492. /**
  2493. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2494. * Returns the current Quaternion.
  2495. */
  2496. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2497. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2498. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2499. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2500. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2501. result.copyFromFloats(x, y, z, w);
  2502. return this;
  2503. };
  2504. /**
  2505. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2506. * Returns the updated Quaternion.
  2507. */
  2508. Quaternion.prototype.multiplyInPlace = function (q1) {
  2509. this.multiplyToRef(q1, this);
  2510. return this;
  2511. };
  2512. /**
  2513. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2514. * Returns the current Quaternion.
  2515. */
  2516. Quaternion.prototype.conjugateToRef = function (ref) {
  2517. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2518. return this;
  2519. };
  2520. /**
  2521. * Conjugates in place the current Quaternion.
  2522. * Returns the updated Quaternion.
  2523. */
  2524. Quaternion.prototype.conjugateInPlace = function () {
  2525. this.x *= -1;
  2526. this.y *= -1;
  2527. this.z *= -1;
  2528. return this;
  2529. };
  2530. /**
  2531. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2532. */
  2533. Quaternion.prototype.conjugate = function () {
  2534. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2535. return result;
  2536. };
  2537. /**
  2538. * Returns the Quaternion length (float).
  2539. */
  2540. Quaternion.prototype.length = function () {
  2541. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2542. };
  2543. /**
  2544. * Normalize in place the current Quaternion.
  2545. * Returns the updated Quaternion.
  2546. */
  2547. Quaternion.prototype.normalize = function () {
  2548. var length = 1.0 / this.length();
  2549. this.x *= length;
  2550. this.y *= length;
  2551. this.z *= length;
  2552. this.w *= length;
  2553. return this;
  2554. };
  2555. /**
  2556. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2557. */
  2558. Quaternion.prototype.toEulerAngles = function (order) {
  2559. if (order === void 0) { order = "YZX"; }
  2560. var result = Vector3.Zero();
  2561. this.toEulerAnglesToRef(result, order);
  2562. return result;
  2563. };
  2564. /**
  2565. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2566. * Returns the current Quaternion.
  2567. */
  2568. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2569. if (order === void 0) { order = "YZX"; }
  2570. var qz = this.z;
  2571. var qx = this.x;
  2572. var qy = this.y;
  2573. var qw = this.w;
  2574. var sqw = qw * qw;
  2575. var sqz = qz * qz;
  2576. var sqx = qx * qx;
  2577. var sqy = qy * qy;
  2578. var zAxisY = qy * qz - qx * qw;
  2579. var limit = .4999999;
  2580. if (zAxisY < -limit) {
  2581. result.y = 2 * Math.atan2(qy, qw);
  2582. result.x = Math.PI / 2;
  2583. result.z = 0;
  2584. }
  2585. else if (zAxisY > limit) {
  2586. result.y = 2 * Math.atan2(qy, qw);
  2587. result.x = -Math.PI / 2;
  2588. result.z = 0;
  2589. }
  2590. else {
  2591. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2592. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2593. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2594. }
  2595. return this;
  2596. };
  2597. /**
  2598. * Updates the passed rotation matrix with the current Quaternion values.
  2599. * Returns the current Quaternion.
  2600. */
  2601. Quaternion.prototype.toRotationMatrix = function (result) {
  2602. var xx = this.x * this.x;
  2603. var yy = this.y * this.y;
  2604. var zz = this.z * this.z;
  2605. var xy = this.x * this.y;
  2606. var zw = this.z * this.w;
  2607. var zx = this.z * this.x;
  2608. var yw = this.y * this.w;
  2609. var yz = this.y * this.z;
  2610. var xw = this.x * this.w;
  2611. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2612. result.m[1] = 2.0 * (xy + zw);
  2613. result.m[2] = 2.0 * (zx - yw);
  2614. result.m[3] = 0;
  2615. result.m[4] = 2.0 * (xy - zw);
  2616. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2617. result.m[6] = 2.0 * (yz + xw);
  2618. result.m[7] = 0;
  2619. result.m[8] = 2.0 * (zx + yw);
  2620. result.m[9] = 2.0 * (yz - xw);
  2621. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2622. result.m[11] = 0;
  2623. result.m[12] = 0;
  2624. result.m[13] = 0;
  2625. result.m[14] = 0;
  2626. result.m[15] = 1.0;
  2627. result._markAsUpdated();
  2628. return this;
  2629. };
  2630. /**
  2631. * Updates the current Quaternion from the passed rotation matrix values.
  2632. * Returns the updated Quaternion.
  2633. */
  2634. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2635. Quaternion.FromRotationMatrixToRef(matrix, this);
  2636. return this;
  2637. };
  2638. // Statics
  2639. /**
  2640. * Returns a new Quaternion set from the passed rotation matrix values.
  2641. */
  2642. Quaternion.FromRotationMatrix = function (matrix) {
  2643. var result = new Quaternion();
  2644. Quaternion.FromRotationMatrixToRef(matrix, result);
  2645. return result;
  2646. };
  2647. /**
  2648. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2649. */
  2650. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2651. var data = matrix.m;
  2652. var m11 = data[0], m12 = data[4], m13 = data[8];
  2653. var m21 = data[1], m22 = data[5], m23 = data[9];
  2654. var m31 = data[2], m32 = data[6], m33 = data[10];
  2655. var trace = m11 + m22 + m33;
  2656. var s;
  2657. if (trace > 0) {
  2658. s = 0.5 / Math.sqrt(trace + 1.0);
  2659. result.w = 0.25 / s;
  2660. result.x = (m32 - m23) * s;
  2661. result.y = (m13 - m31) * s;
  2662. result.z = (m21 - m12) * s;
  2663. }
  2664. else if (m11 > m22 && m11 > m33) {
  2665. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2666. result.w = (m32 - m23) / s;
  2667. result.x = 0.25 * s;
  2668. result.y = (m12 + m21) / s;
  2669. result.z = (m13 + m31) / s;
  2670. }
  2671. else if (m22 > m33) {
  2672. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2673. result.w = (m13 - m31) / s;
  2674. result.x = (m12 + m21) / s;
  2675. result.y = 0.25 * s;
  2676. result.z = (m23 + m32) / s;
  2677. }
  2678. else {
  2679. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2680. result.w = (m21 - m12) / s;
  2681. result.x = (m13 + m31) / s;
  2682. result.y = (m23 + m32) / s;
  2683. result.z = 0.25 * s;
  2684. }
  2685. };
  2686. /**
  2687. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2688. */
  2689. Quaternion.Zero = function () {
  2690. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2691. };
  2692. /**
  2693. * Returns a new Quaternion as the inverted current Quaternion.
  2694. */
  2695. Quaternion.Inverse = function (q) {
  2696. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2697. };
  2698. /**
  2699. * Returns the identity Quaternion.
  2700. */
  2701. Quaternion.Identity = function () {
  2702. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2703. };
  2704. Quaternion.IsIdentity = function (quaternion) {
  2705. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2706. };
  2707. /**
  2708. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2709. */
  2710. Quaternion.RotationAxis = function (axis, angle) {
  2711. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2712. };
  2713. /**
  2714. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2715. */
  2716. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2717. var sin = Math.sin(angle / 2);
  2718. axis.normalize();
  2719. result.w = Math.cos(angle / 2);
  2720. result.x = axis.x * sin;
  2721. result.y = axis.y * sin;
  2722. result.z = axis.z * sin;
  2723. return result;
  2724. };
  2725. /**
  2726. * Retuns a new Quaternion set from the starting index of the passed array.
  2727. */
  2728. Quaternion.FromArray = function (array, offset) {
  2729. if (!offset) {
  2730. offset = 0;
  2731. }
  2732. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2733. };
  2734. /**
  2735. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2736. */
  2737. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2738. var q = new Quaternion();
  2739. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2740. return q;
  2741. };
  2742. /**
  2743. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2744. */
  2745. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2746. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2747. var halfRoll = roll * 0.5;
  2748. var halfPitch = pitch * 0.5;
  2749. var halfYaw = yaw * 0.5;
  2750. var sinRoll = Math.sin(halfRoll);
  2751. var cosRoll = Math.cos(halfRoll);
  2752. var sinPitch = Math.sin(halfPitch);
  2753. var cosPitch = Math.cos(halfPitch);
  2754. var sinYaw = Math.sin(halfYaw);
  2755. var cosYaw = Math.cos(halfYaw);
  2756. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2757. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2758. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2759. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2760. };
  2761. /**
  2762. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2763. */
  2764. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2765. var result = new Quaternion();
  2766. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2767. return result;
  2768. };
  2769. /**
  2770. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2771. */
  2772. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2773. // Produces a quaternion from Euler angles in the z-x-z orientation
  2774. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2775. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2776. var halfBeta = beta * 0.5;
  2777. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2778. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2779. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2780. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2781. };
  2782. /**
  2783. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2784. * cf to Vector3.RotationFromAxis() documentation.
  2785. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2786. */
  2787. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2788. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2789. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2790. return quat;
  2791. };
  2792. /**
  2793. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2794. * cf to Vector3.RotationFromAxis() documentation.
  2795. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2796. */
  2797. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2798. var rotMat = MathTmp.Matrix[0];
  2799. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2800. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2801. };
  2802. Quaternion.Slerp = function (left, right, amount) {
  2803. var result = Quaternion.Identity();
  2804. Quaternion.SlerpToRef(left, right, amount, result);
  2805. return result;
  2806. };
  2807. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2808. var num2;
  2809. var num3;
  2810. var num = amount;
  2811. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2812. var flag = false;
  2813. if (num4 < 0) {
  2814. flag = true;
  2815. num4 = -num4;
  2816. }
  2817. if (num4 > 0.999999) {
  2818. num3 = 1 - num;
  2819. num2 = flag ? -num : num;
  2820. }
  2821. else {
  2822. var num5 = Math.acos(num4);
  2823. var num6 = (1.0 / Math.sin(num5));
  2824. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2825. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2826. }
  2827. result.x = (num3 * left.x) + (num2 * right.x);
  2828. result.y = (num3 * left.y) + (num2 * right.y);
  2829. result.z = (num3 * left.z) + (num2 * right.z);
  2830. result.w = (num3 * left.w) + (num2 * right.w);
  2831. };
  2832. /**
  2833. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2834. */
  2835. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2836. var squared = amount * amount;
  2837. var cubed = amount * squared;
  2838. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2839. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2840. var part3 = (cubed - (2.0 * squared)) + amount;
  2841. var part4 = cubed - squared;
  2842. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2843. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2844. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2845. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2846. return new Quaternion(x, y, z, w);
  2847. };
  2848. return Quaternion;
  2849. }());
  2850. BABYLON.Quaternion = Quaternion;
  2851. var Matrix = (function () {
  2852. function Matrix() {
  2853. this._isIdentity = false;
  2854. this._isIdentityDirty = true;
  2855. this.m = new Float32Array(16);
  2856. this._markAsUpdated();
  2857. }
  2858. Matrix.prototype._markAsUpdated = function () {
  2859. this.updateFlag = Matrix._updateFlagSeed++;
  2860. this._isIdentityDirty = true;
  2861. };
  2862. // Properties
  2863. /**
  2864. * Boolean : True is the matrix is the identity matrix
  2865. */
  2866. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2867. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2868. if (this._isIdentityDirty) {
  2869. this._isIdentityDirty = false;
  2870. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2871. this._isIdentity = false;
  2872. }
  2873. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2874. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2875. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2876. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2877. this._isIdentity = false;
  2878. }
  2879. else {
  2880. this._isIdentity = true;
  2881. }
  2882. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2883. this._isIdentity = false;
  2884. }
  2885. }
  2886. return this._isIdentity;
  2887. };
  2888. /**
  2889. * Returns the matrix determinant (float).
  2890. */
  2891. Matrix.prototype.determinant = function () {
  2892. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2893. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2894. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2895. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2896. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2897. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2898. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2899. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2900. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2901. };
  2902. // Methods
  2903. /**
  2904. * Returns the matrix underlying array.
  2905. */
  2906. Matrix.prototype.toArray = function () {
  2907. return this.m;
  2908. };
  2909. /**
  2910. * Returns the matrix underlying array.
  2911. */
  2912. Matrix.prototype.asArray = function () {
  2913. return this.toArray();
  2914. };
  2915. /**
  2916. * Inverts in place the Matrix.
  2917. * Returns the Matrix inverted.
  2918. */
  2919. Matrix.prototype.invert = function () {
  2920. this.invertToRef(this);
  2921. return this;
  2922. };
  2923. /**
  2924. * Sets all the matrix elements to zero.
  2925. * Returns the Matrix.
  2926. */
  2927. Matrix.prototype.reset = function () {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = 0.0;
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2936. */
  2937. Matrix.prototype.add = function (other) {
  2938. var result = new Matrix();
  2939. this.addToRef(other, result);
  2940. return result;
  2941. };
  2942. /**
  2943. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.addToRef = function (other, result) {
  2947. for (var index = 0; index < 16; index++) {
  2948. result.m[index] = this.m[index] + other.m[index];
  2949. }
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Adds in place the passed matrix to the current Matrix.
  2955. * Returns the updated Matrix.
  2956. */
  2957. Matrix.prototype.addToSelf = function (other) {
  2958. for (var index = 0; index < 16; index++) {
  2959. this.m[index] += other.m[index];
  2960. }
  2961. this._markAsUpdated();
  2962. return this;
  2963. };
  2964. /**
  2965. * Sets the passed matrix with the current inverted Matrix.
  2966. * Returns the unmodified current Matrix.
  2967. */
  2968. Matrix.prototype.invertToRef = function (other) {
  2969. var l1 = this.m[0];
  2970. var l2 = this.m[1];
  2971. var l3 = this.m[2];
  2972. var l4 = this.m[3];
  2973. var l5 = this.m[4];
  2974. var l6 = this.m[5];
  2975. var l7 = this.m[6];
  2976. var l8 = this.m[7];
  2977. var l9 = this.m[8];
  2978. var l10 = this.m[9];
  2979. var l11 = this.m[10];
  2980. var l12 = this.m[11];
  2981. var l13 = this.m[12];
  2982. var l14 = this.m[13];
  2983. var l15 = this.m[14];
  2984. var l16 = this.m[15];
  2985. var l17 = (l11 * l16) - (l12 * l15);
  2986. var l18 = (l10 * l16) - (l12 * l14);
  2987. var l19 = (l10 * l15) - (l11 * l14);
  2988. var l20 = (l9 * l16) - (l12 * l13);
  2989. var l21 = (l9 * l15) - (l11 * l13);
  2990. var l22 = (l9 * l14) - (l10 * l13);
  2991. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2992. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2993. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2994. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2995. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2996. var l28 = (l7 * l16) - (l8 * l15);
  2997. var l29 = (l6 * l16) - (l8 * l14);
  2998. var l30 = (l6 * l15) - (l7 * l14);
  2999. var l31 = (l5 * l16) - (l8 * l13);
  3000. var l32 = (l5 * l15) - (l7 * l13);
  3001. var l33 = (l5 * l14) - (l6 * l13);
  3002. var l34 = (l7 * l12) - (l8 * l11);
  3003. var l35 = (l6 * l12) - (l8 * l10);
  3004. var l36 = (l6 * l11) - (l7 * l10);
  3005. var l37 = (l5 * l12) - (l8 * l9);
  3006. var l38 = (l5 * l11) - (l7 * l9);
  3007. var l39 = (l5 * l10) - (l6 * l9);
  3008. other.m[0] = l23 * l27;
  3009. other.m[4] = l24 * l27;
  3010. other.m[8] = l25 * l27;
  3011. other.m[12] = l26 * l27;
  3012. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3013. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3014. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3015. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3016. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3017. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3018. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3019. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3020. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3021. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3022. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3023. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3024. other._markAsUpdated();
  3025. return this;
  3026. };
  3027. /**
  3028. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3029. * Returns the updated Matrix.
  3030. */
  3031. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3032. this.m[12] = x;
  3033. this.m[13] = y;
  3034. this.m[14] = z;
  3035. this._markAsUpdated();
  3036. return this;
  3037. };
  3038. /**
  3039. * Inserts the translation vector in the current Matrix.
  3040. * Returns the updated Matrix.
  3041. */
  3042. Matrix.prototype.setTranslation = function (vector3) {
  3043. this.m[12] = vector3.x;
  3044. this.m[13] = vector3.y;
  3045. this.m[14] = vector3.z;
  3046. this._markAsUpdated();
  3047. return this;
  3048. };
  3049. /**
  3050. * Returns a new Vector3 as the extracted translation from the Matrix.
  3051. */
  3052. Matrix.prototype.getTranslation = function () {
  3053. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3054. };
  3055. /**
  3056. * Fill a Vector3 with the extracted translation from the Matrix.
  3057. */
  3058. Matrix.prototype.getTranslationToRef = function (result) {
  3059. result.x = this.m[12];
  3060. result.y = this.m[13];
  3061. result.z = this.m[14];
  3062. return this;
  3063. };
  3064. /**
  3065. * Remove rotation and scaling part from the Matrix.
  3066. * Returns the updated Matrix.
  3067. */
  3068. Matrix.prototype.removeRotationAndScaling = function () {
  3069. this.setRowFromFloats(0, 1, 0, 0, 0);
  3070. this.setRowFromFloats(1, 0, 1, 0, 0);
  3071. this.setRowFromFloats(2, 0, 0, 1, 0);
  3072. return this;
  3073. };
  3074. /**
  3075. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3076. */
  3077. Matrix.prototype.multiply = function (other) {
  3078. var result = new Matrix();
  3079. this.multiplyToRef(other, result);
  3080. return result;
  3081. };
  3082. /**
  3083. * Updates the current Matrix from the passed one values.
  3084. * Returns the updated Matrix.
  3085. */
  3086. Matrix.prototype.copyFrom = function (other) {
  3087. for (var index = 0; index < 16; index++) {
  3088. this.m[index] = other.m[index];
  3089. }
  3090. this._markAsUpdated();
  3091. return this;
  3092. };
  3093. /**
  3094. * Populates the passed array from the starting index with the Matrix values.
  3095. * Returns the Matrix.
  3096. */
  3097. Matrix.prototype.copyToArray = function (array, offset) {
  3098. if (offset === void 0) { offset = 0; }
  3099. for (var index = 0; index < 16; index++) {
  3100. array[offset + index] = this.m[index];
  3101. }
  3102. return this;
  3103. };
  3104. /**
  3105. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3106. */
  3107. Matrix.prototype.multiplyToRef = function (other, result) {
  3108. this.multiplyToArray(other, result.m, 0);
  3109. result._markAsUpdated();
  3110. return this;
  3111. };
  3112. /**
  3113. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3114. */
  3115. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3116. var tm0 = this.m[0];
  3117. var tm1 = this.m[1];
  3118. var tm2 = this.m[2];
  3119. var tm3 = this.m[3];
  3120. var tm4 = this.m[4];
  3121. var tm5 = this.m[5];
  3122. var tm6 = this.m[6];
  3123. var tm7 = this.m[7];
  3124. var tm8 = this.m[8];
  3125. var tm9 = this.m[9];
  3126. var tm10 = this.m[10];
  3127. var tm11 = this.m[11];
  3128. var tm12 = this.m[12];
  3129. var tm13 = this.m[13];
  3130. var tm14 = this.m[14];
  3131. var tm15 = this.m[15];
  3132. var om0 = other.m[0];
  3133. var om1 = other.m[1];
  3134. var om2 = other.m[2];
  3135. var om3 = other.m[3];
  3136. var om4 = other.m[4];
  3137. var om5 = other.m[5];
  3138. var om6 = other.m[6];
  3139. var om7 = other.m[7];
  3140. var om8 = other.m[8];
  3141. var om9 = other.m[9];
  3142. var om10 = other.m[10];
  3143. var om11 = other.m[11];
  3144. var om12 = other.m[12];
  3145. var om13 = other.m[13];
  3146. var om14 = other.m[14];
  3147. var om15 = other.m[15];
  3148. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3149. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3150. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3151. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3152. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3153. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3154. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3155. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3156. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3157. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3158. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3159. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3160. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3161. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3162. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3163. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3164. return this;
  3165. };
  3166. /**
  3167. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3168. */
  3169. Matrix.prototype.equals = function (value) {
  3170. return value &&
  3171. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3172. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3173. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3174. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3175. };
  3176. /**
  3177. * Returns a new Matrix from the current Matrix.
  3178. */
  3179. Matrix.prototype.clone = function () {
  3180. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  3181. };
  3182. /**
  3183. * Returns the string "Matrix"
  3184. */
  3185. Matrix.prototype.getClassName = function () {
  3186. return "Matrix";
  3187. };
  3188. /**
  3189. * Returns the Matrix hash code.
  3190. */
  3191. Matrix.prototype.getHashCode = function () {
  3192. var hash = this.m[0] || 0;
  3193. for (var i = 1; i < 16; i++) {
  3194. hash = (hash * 397) ^ (this.m[i] || 0);
  3195. }
  3196. return hash;
  3197. };
  3198. /**
  3199. * Decomposes the current Matrix into :
  3200. * - a scale vector3 passed as a reference to update,
  3201. * - a rotation quaternion passed as a reference to update,
  3202. * - a translation vector3 passed as a reference to update.
  3203. * Returns the boolean `true`.
  3204. */
  3205. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3206. translation.x = this.m[12];
  3207. translation.y = this.m[13];
  3208. translation.z = this.m[14];
  3209. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3210. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3211. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3212. if (this.determinant() <= 0) {
  3213. scale.y *= -1;
  3214. }
  3215. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3216. rotation.x = 0;
  3217. rotation.y = 0;
  3218. rotation.z = 0;
  3219. rotation.w = 1;
  3220. return false;
  3221. }
  3222. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3223. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3224. return true;
  3225. };
  3226. /**
  3227. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3228. */
  3229. Matrix.prototype.getRotationMatrix = function () {
  3230. var result = Matrix.Identity();
  3231. this.getRotationMatrixToRef(result);
  3232. return result;
  3233. };
  3234. /**
  3235. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3236. * Returns the current Matrix.
  3237. */
  3238. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3239. var m = this.m;
  3240. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3241. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3242. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3243. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3244. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3245. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3246. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3247. return this;
  3248. };
  3249. // Statics
  3250. /**
  3251. * Returns a new Matrix set from the starting index of the passed array.
  3252. */
  3253. Matrix.FromArray = function (array, offset) {
  3254. var result = new Matrix();
  3255. if (!offset) {
  3256. offset = 0;
  3257. }
  3258. Matrix.FromArrayToRef(array, offset, result);
  3259. return result;
  3260. };
  3261. /**
  3262. * Sets the passed "result" matrix from the starting index of the passed array.
  3263. */
  3264. Matrix.FromArrayToRef = function (array, offset, result) {
  3265. for (var index = 0; index < 16; index++) {
  3266. result.m[index] = array[index + offset];
  3267. }
  3268. result._markAsUpdated();
  3269. };
  3270. /**
  3271. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3272. */
  3273. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3274. for (var index = 0; index < 16; index++) {
  3275. result.m[index] = array[index + offset] * scale;
  3276. }
  3277. result._markAsUpdated();
  3278. };
  3279. /**
  3280. * Sets the passed matrix "result" with the 16 passed floats.
  3281. */
  3282. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3283. result.m[0] = initialM11;
  3284. result.m[1] = initialM12;
  3285. result.m[2] = initialM13;
  3286. result.m[3] = initialM14;
  3287. result.m[4] = initialM21;
  3288. result.m[5] = initialM22;
  3289. result.m[6] = initialM23;
  3290. result.m[7] = initialM24;
  3291. result.m[8] = initialM31;
  3292. result.m[9] = initialM32;
  3293. result.m[10] = initialM33;
  3294. result.m[11] = initialM34;
  3295. result.m[12] = initialM41;
  3296. result.m[13] = initialM42;
  3297. result.m[14] = initialM43;
  3298. result.m[15] = initialM44;
  3299. result._markAsUpdated();
  3300. };
  3301. /**
  3302. * Returns the index-th row of the current matrix as a new Vector4.
  3303. */
  3304. Matrix.prototype.getRow = function (index) {
  3305. if (index < 0 || index > 3) {
  3306. return null;
  3307. }
  3308. var i = index * 4;
  3309. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3310. };
  3311. /**
  3312. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3313. * Returns the updated Matrix.
  3314. */
  3315. Matrix.prototype.setRow = function (index, row) {
  3316. if (index < 0 || index > 3) {
  3317. return this;
  3318. }
  3319. var i = index * 4;
  3320. this.m[i + 0] = row.x;
  3321. this.m[i + 1] = row.y;
  3322. this.m[i + 2] = row.z;
  3323. this.m[i + 3] = row.w;
  3324. this._markAsUpdated();
  3325. return this;
  3326. };
  3327. /**
  3328. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3329. * Returns the updated Matrix.
  3330. */
  3331. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3332. if (index < 0 || index > 3) {
  3333. return this;
  3334. }
  3335. var i = index * 4;
  3336. this.m[i + 0] = x;
  3337. this.m[i + 1] = y;
  3338. this.m[i + 2] = z;
  3339. this.m[i + 3] = w;
  3340. this._markAsUpdated();
  3341. return this;
  3342. };
  3343. /**
  3344. * Returns a new Matrix set from the 16 passed floats.
  3345. */
  3346. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3347. var result = new Matrix();
  3348. result.m[0] = initialM11;
  3349. result.m[1] = initialM12;
  3350. result.m[2] = initialM13;
  3351. result.m[3] = initialM14;
  3352. result.m[4] = initialM21;
  3353. result.m[5] = initialM22;
  3354. result.m[6] = initialM23;
  3355. result.m[7] = initialM24;
  3356. result.m[8] = initialM31;
  3357. result.m[9] = initialM32;
  3358. result.m[10] = initialM33;
  3359. result.m[11] = initialM34;
  3360. result.m[12] = initialM41;
  3361. result.m[13] = initialM42;
  3362. result.m[14] = initialM43;
  3363. result.m[15] = initialM44;
  3364. return result;
  3365. };
  3366. /**
  3367. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3368. */
  3369. Matrix.Compose = function (scale, rotation, translation) {
  3370. var result = Matrix.Identity();
  3371. Matrix.ComposeToRef(scale, rotation, translation, result);
  3372. return result;
  3373. };
  3374. /**
  3375. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3376. */
  3377. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3378. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3379. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3380. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3381. result.setTranslation(translation);
  3382. };
  3383. /**
  3384. * Returns a new indentity Matrix.
  3385. */
  3386. Matrix.Identity = function () {
  3387. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3388. };
  3389. /**
  3390. * Sets the passed "result" as an identity matrix.
  3391. */
  3392. Matrix.IdentityToRef = function (result) {
  3393. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3394. };
  3395. /**
  3396. * Returns a new zero Matrix.
  3397. */
  3398. Matrix.Zero = function () {
  3399. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3400. };
  3401. /**
  3402. * Returns a new rotation matrix for "angle" radians around the X axis.
  3403. */
  3404. Matrix.RotationX = function (angle) {
  3405. var result = new Matrix();
  3406. Matrix.RotationXToRef(angle, result);
  3407. return result;
  3408. };
  3409. /**
  3410. * Returns a new Matrix as the passed inverted one.
  3411. */
  3412. Matrix.Invert = function (source) {
  3413. var result = new Matrix();
  3414. source.invertToRef(result);
  3415. return result;
  3416. };
  3417. /**
  3418. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3419. */
  3420. Matrix.RotationXToRef = function (angle, result) {
  3421. var s = Math.sin(angle);
  3422. var c = Math.cos(angle);
  3423. result.m[0] = 1.0;
  3424. result.m[15] = 1.0;
  3425. result.m[5] = c;
  3426. result.m[10] = c;
  3427. result.m[9] = -s;
  3428. result.m[6] = s;
  3429. result.m[1] = 0.0;
  3430. result.m[2] = 0.0;
  3431. result.m[3] = 0.0;
  3432. result.m[4] = 0.0;
  3433. result.m[7] = 0.0;
  3434. result.m[8] = 0.0;
  3435. result.m[11] = 0.0;
  3436. result.m[12] = 0.0;
  3437. result.m[13] = 0.0;
  3438. result.m[14] = 0.0;
  3439. result._markAsUpdated();
  3440. };
  3441. /**
  3442. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3443. */
  3444. Matrix.RotationY = function (angle) {
  3445. var result = new Matrix();
  3446. Matrix.RotationYToRef(angle, result);
  3447. return result;
  3448. };
  3449. /**
  3450. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3451. */
  3452. Matrix.RotationYToRef = function (angle, result) {
  3453. var s = Math.sin(angle);
  3454. var c = Math.cos(angle);
  3455. result.m[5] = 1.0;
  3456. result.m[15] = 1.0;
  3457. result.m[0] = c;
  3458. result.m[2] = -s;
  3459. result.m[8] = s;
  3460. result.m[10] = c;
  3461. result.m[1] = 0.0;
  3462. result.m[3] = 0.0;
  3463. result.m[4] = 0.0;
  3464. result.m[6] = 0.0;
  3465. result.m[7] = 0.0;
  3466. result.m[9] = 0.0;
  3467. result.m[11] = 0.0;
  3468. result.m[12] = 0.0;
  3469. result.m[13] = 0.0;
  3470. result.m[14] = 0.0;
  3471. result._markAsUpdated();
  3472. };
  3473. /**
  3474. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3475. */
  3476. Matrix.RotationZ = function (angle) {
  3477. var result = new Matrix();
  3478. Matrix.RotationZToRef(angle, result);
  3479. return result;
  3480. };
  3481. /**
  3482. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3483. */
  3484. Matrix.RotationZToRef = function (angle, result) {
  3485. var s = Math.sin(angle);
  3486. var c = Math.cos(angle);
  3487. result.m[10] = 1.0;
  3488. result.m[15] = 1.0;
  3489. result.m[0] = c;
  3490. result.m[1] = s;
  3491. result.m[4] = -s;
  3492. result.m[5] = c;
  3493. result.m[2] = 0.0;
  3494. result.m[3] = 0.0;
  3495. result.m[6] = 0.0;
  3496. result.m[7] = 0.0;
  3497. result.m[8] = 0.0;
  3498. result.m[9] = 0.0;
  3499. result.m[11] = 0.0;
  3500. result.m[12] = 0.0;
  3501. result.m[13] = 0.0;
  3502. result.m[14] = 0.0;
  3503. result._markAsUpdated();
  3504. };
  3505. /**
  3506. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3507. */
  3508. Matrix.RotationAxis = function (axis, angle) {
  3509. var result = Matrix.Zero();
  3510. Matrix.RotationAxisToRef(axis, angle, result);
  3511. return result;
  3512. };
  3513. /**
  3514. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3515. */
  3516. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3517. var s = Math.sin(-angle);
  3518. var c = Math.cos(-angle);
  3519. var c1 = 1 - c;
  3520. axis.normalize();
  3521. result.m[0] = (axis.x * axis.x) * c1 + c;
  3522. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3523. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3524. result.m[3] = 0.0;
  3525. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3526. result.m[5] = (axis.y * axis.y) * c1 + c;
  3527. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3528. result.m[7] = 0.0;
  3529. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3530. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3531. result.m[10] = (axis.z * axis.z) * c1 + c;
  3532. result.m[11] = 0.0;
  3533. result.m[15] = 1.0;
  3534. result._markAsUpdated();
  3535. };
  3536. /**
  3537. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3538. */
  3539. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3540. var result = new Matrix();
  3541. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3542. return result;
  3543. };
  3544. /**
  3545. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3546. */
  3547. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3548. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3549. this._tempQuaternion.toRotationMatrix(result);
  3550. };
  3551. /**
  3552. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3553. */
  3554. Matrix.Scaling = function (x, y, z) {
  3555. var result = Matrix.Zero();
  3556. Matrix.ScalingToRef(x, y, z, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3561. */
  3562. Matrix.ScalingToRef = function (x, y, z, result) {
  3563. result.m[0] = x;
  3564. result.m[1] = 0.0;
  3565. result.m[2] = 0.0;
  3566. result.m[3] = 0.0;
  3567. result.m[4] = 0.0;
  3568. result.m[5] = y;
  3569. result.m[6] = 0.0;
  3570. result.m[7] = 0.0;
  3571. result.m[8] = 0.0;
  3572. result.m[9] = 0.0;
  3573. result.m[10] = z;
  3574. result.m[11] = 0.0;
  3575. result.m[12] = 0.0;
  3576. result.m[13] = 0.0;
  3577. result.m[14] = 0.0;
  3578. result.m[15] = 1.0;
  3579. result._markAsUpdated();
  3580. };
  3581. /**
  3582. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3583. */
  3584. Matrix.Translation = function (x, y, z) {
  3585. var result = Matrix.Identity();
  3586. Matrix.TranslationToRef(x, y, z, result);
  3587. return result;
  3588. };
  3589. /**
  3590. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3591. */
  3592. Matrix.TranslationToRef = function (x, y, z, result) {
  3593. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3594. };
  3595. /**
  3596. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3597. */
  3598. Matrix.Lerp = function (startValue, endValue, gradient) {
  3599. var result = Matrix.Zero();
  3600. for (var index = 0; index < 16; index++) {
  3601. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3602. }
  3603. result._markAsUpdated();
  3604. return result;
  3605. };
  3606. /**
  3607. * Returns a new Matrix whose values are computed by :
  3608. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3609. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3610. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3611. */
  3612. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3613. var startScale = new Vector3(0, 0, 0);
  3614. var startRotation = new Quaternion();
  3615. var startTranslation = new Vector3(0, 0, 0);
  3616. startValue.decompose(startScale, startRotation, startTranslation);
  3617. var endScale = new Vector3(0, 0, 0);
  3618. var endRotation = new Quaternion();
  3619. var endTranslation = new Vector3(0, 0, 0);
  3620. endValue.decompose(endScale, endRotation, endTranslation);
  3621. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3622. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3623. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3624. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3625. };
  3626. /**
  3627. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3628. * This methods works for a Left-Handed system.
  3629. */
  3630. Matrix.LookAtLH = function (eye, target, up) {
  3631. var result = Matrix.Zero();
  3632. Matrix.LookAtLHToRef(eye, target, up, result);
  3633. return result;
  3634. };
  3635. /**
  3636. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3637. * This methods works for a Left-Handed system.
  3638. */
  3639. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3640. // Z axis
  3641. target.subtractToRef(eye, this._zAxis);
  3642. this._zAxis.normalize();
  3643. // X axis
  3644. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3645. if (this._xAxis.lengthSquared() === 0) {
  3646. this._xAxis.x = 1.0;
  3647. }
  3648. else {
  3649. this._xAxis.normalize();
  3650. }
  3651. // Y axis
  3652. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3653. this._yAxis.normalize();
  3654. // Eye angles
  3655. var ex = -Vector3.Dot(this._xAxis, eye);
  3656. var ey = -Vector3.Dot(this._yAxis, eye);
  3657. var ez = -Vector3.Dot(this._zAxis, eye);
  3658. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3659. };
  3660. /**
  3661. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3662. * This methods works for a Right-Handed system.
  3663. */
  3664. Matrix.LookAtRH = function (eye, target, up) {
  3665. var result = Matrix.Zero();
  3666. Matrix.LookAtRHToRef(eye, target, up, result);
  3667. return result;
  3668. };
  3669. /**
  3670. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3671. * This methods works for a Left-Handed system.
  3672. */
  3673. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3674. // Z axis
  3675. eye.subtractToRef(target, this._zAxis);
  3676. this._zAxis.normalize();
  3677. // X axis
  3678. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3679. if (this._xAxis.lengthSquared() === 0) {
  3680. this._xAxis.x = 1.0;
  3681. }
  3682. else {
  3683. this._xAxis.normalize();
  3684. }
  3685. // Y axis
  3686. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3687. this._yAxis.normalize();
  3688. // Eye angles
  3689. var ex = -Vector3.Dot(this._xAxis, eye);
  3690. var ey = -Vector3.Dot(this._yAxis, eye);
  3691. var ez = -Vector3.Dot(this._zAxis, eye);
  3692. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3693. };
  3694. /**
  3695. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3696. */
  3697. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3698. var matrix = Matrix.Zero();
  3699. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3700. return matrix;
  3701. };
  3702. /**
  3703. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3704. */
  3705. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3706. var n = znear;
  3707. var f = zfar;
  3708. var a = 2.0 / width;
  3709. var b = 2.0 / height;
  3710. var c = 2.0 / (f - n);
  3711. var d = -(f + n) / (f - n);
  3712. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3713. };
  3714. /**
  3715. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3716. */
  3717. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3718. var matrix = Matrix.Zero();
  3719. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3720. return matrix;
  3721. };
  3722. /**
  3723. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3724. */
  3725. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3726. var n = znear;
  3727. var f = zfar;
  3728. var a = 2.0 / (right - left);
  3729. var b = 2.0 / (top - bottom);
  3730. var c = 2.0 / (f - n);
  3731. var d = -(f + n) / (f - n);
  3732. var i0 = (left + right) / (left - right);
  3733. var i1 = (top + bottom) / (bottom - top);
  3734. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3735. };
  3736. /**
  3737. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3738. */
  3739. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3740. var matrix = Matrix.Zero();
  3741. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3742. return matrix;
  3743. };
  3744. /**
  3745. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3746. */
  3747. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3748. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3749. result.m[10] *= -1.0;
  3750. };
  3751. /**
  3752. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3753. */
  3754. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3755. var matrix = Matrix.Zero();
  3756. var n = znear;
  3757. var f = zfar;
  3758. var a = 2.0 * n / width;
  3759. var b = 2.0 * n / height;
  3760. var c = (f + n) / (f - n);
  3761. var d = -2.0 * f * n / (f - n);
  3762. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3763. return matrix;
  3764. };
  3765. /**
  3766. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3767. */
  3768. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3769. var matrix = Matrix.Zero();
  3770. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3771. return matrix;
  3772. };
  3773. /**
  3774. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3775. */
  3776. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3777. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3778. var n = znear;
  3779. var f = zfar;
  3780. var t = 1.0 / (Math.tan(fov * 0.5));
  3781. var a = isVerticalFovFixed ? (t / aspect) : t;
  3782. var b = isVerticalFovFixed ? t : (t * aspect);
  3783. var c = (f + n) / (f - n);
  3784. var d = -2.0 * f * n / (f - n);
  3785. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3786. };
  3787. /**
  3788. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3789. */
  3790. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3791. var matrix = Matrix.Zero();
  3792. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3793. return matrix;
  3794. };
  3795. /**
  3796. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3797. */
  3798. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3799. //alternatively this could be expressed as:
  3800. // m = PerspectiveFovLHToRef
  3801. // m[10] *= -1.0;
  3802. // m[11] *= -1.0;
  3803. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3804. var n = znear;
  3805. var f = zfar;
  3806. var t = 1.0 / (Math.tan(fov * 0.5));
  3807. var a = isVerticalFovFixed ? (t / aspect) : t;
  3808. var b = isVerticalFovFixed ? t : (t * aspect);
  3809. var c = -(f + n) / (f - n);
  3810. var d = -2 * f * n / (f - n);
  3811. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3812. };
  3813. /**
  3814. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3815. */
  3816. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3817. if (rightHanded === void 0) { rightHanded = false; }
  3818. var rightHandedFactor = rightHanded ? -1 : 1;
  3819. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3820. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3821. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3822. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3823. var xScale = 2.0 / (leftTan + rightTan);
  3824. var yScale = 2.0 / (upTan + downTan);
  3825. result.m[0] = xScale;
  3826. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3827. result.m[5] = yScale;
  3828. result.m[6] = result.m[7] = 0.0;
  3829. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3830. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3831. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3832. result.m[10] = -zfar / (znear - zfar);
  3833. result.m[11] = 1.0 * rightHandedFactor;
  3834. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3835. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3836. // result.m[14] = (znear * zfar) / (znear - zfar);
  3837. result._markAsUpdated();
  3838. };
  3839. /**
  3840. * Returns the final transformation matrix : world * view * projection * viewport
  3841. */
  3842. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3843. var cw = viewport.width;
  3844. var ch = viewport.height;
  3845. var cx = viewport.x;
  3846. var cy = viewport.y;
  3847. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3848. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3849. };
  3850. /**
  3851. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3852. */
  3853. Matrix.GetAsMatrix2x2 = function (matrix) {
  3854. return new Float32Array([
  3855. matrix.m[0], matrix.m[1],
  3856. matrix.m[4], matrix.m[5]
  3857. ]);
  3858. };
  3859. /**
  3860. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3861. */
  3862. Matrix.GetAsMatrix3x3 = function (matrix) {
  3863. return new Float32Array([
  3864. matrix.m[0], matrix.m[1], matrix.m[2],
  3865. matrix.m[4], matrix.m[5], matrix.m[6],
  3866. matrix.m[8], matrix.m[9], matrix.m[10]
  3867. ]);
  3868. };
  3869. /**
  3870. * Compute the transpose of the passed Matrix.
  3871. * Returns a new Matrix.
  3872. */
  3873. Matrix.Transpose = function (matrix) {
  3874. var result = new Matrix();
  3875. result.m[0] = matrix.m[0];
  3876. result.m[1] = matrix.m[4];
  3877. result.m[2] = matrix.m[8];
  3878. result.m[3] = matrix.m[12];
  3879. result.m[4] = matrix.m[1];
  3880. result.m[5] = matrix.m[5];
  3881. result.m[6] = matrix.m[9];
  3882. result.m[7] = matrix.m[13];
  3883. result.m[8] = matrix.m[2];
  3884. result.m[9] = matrix.m[6];
  3885. result.m[10] = matrix.m[10];
  3886. result.m[11] = matrix.m[14];
  3887. result.m[12] = matrix.m[3];
  3888. result.m[13] = matrix.m[7];
  3889. result.m[14] = matrix.m[11];
  3890. result.m[15] = matrix.m[15];
  3891. return result;
  3892. };
  3893. /**
  3894. * Returns a new Matrix as the reflection matrix across the passed plane.
  3895. */
  3896. Matrix.Reflection = function (plane) {
  3897. var matrix = new Matrix();
  3898. Matrix.ReflectionToRef(plane, matrix);
  3899. return matrix;
  3900. };
  3901. /**
  3902. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3903. */
  3904. Matrix.ReflectionToRef = function (plane, result) {
  3905. plane.normalize();
  3906. var x = plane.normal.x;
  3907. var y = plane.normal.y;
  3908. var z = plane.normal.z;
  3909. var temp = -2 * x;
  3910. var temp2 = -2 * y;
  3911. var temp3 = -2 * z;
  3912. result.m[0] = (temp * x) + 1;
  3913. result.m[1] = temp2 * x;
  3914. result.m[2] = temp3 * x;
  3915. result.m[3] = 0.0;
  3916. result.m[4] = temp * y;
  3917. result.m[5] = (temp2 * y) + 1;
  3918. result.m[6] = temp3 * y;
  3919. result.m[7] = 0.0;
  3920. result.m[8] = temp * z;
  3921. result.m[9] = temp2 * z;
  3922. result.m[10] = (temp3 * z) + 1;
  3923. result.m[11] = 0.0;
  3924. result.m[12] = temp * plane.d;
  3925. result.m[13] = temp2 * plane.d;
  3926. result.m[14] = temp3 * plane.d;
  3927. result.m[15] = 1.0;
  3928. result._markAsUpdated();
  3929. };
  3930. /**
  3931. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3932. */
  3933. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3934. result.m[0] = xaxis.x;
  3935. result.m[1] = xaxis.y;
  3936. result.m[2] = xaxis.z;
  3937. result.m[3] = 0.0;
  3938. result.m[4] = yaxis.x;
  3939. result.m[5] = yaxis.y;
  3940. result.m[6] = yaxis.z;
  3941. result.m[7] = 0.0;
  3942. result.m[8] = zaxis.x;
  3943. result.m[9] = zaxis.y;
  3944. result.m[10] = zaxis.z;
  3945. result.m[11] = 0.0;
  3946. result.m[12] = 0.0;
  3947. result.m[13] = 0.0;
  3948. result.m[14] = 0.0;
  3949. result.m[15] = 1.0;
  3950. result._markAsUpdated();
  3951. };
  3952. /**
  3953. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3954. */
  3955. Matrix.FromQuaternionToRef = function (quat, result) {
  3956. var xx = quat.x * quat.x;
  3957. var yy = quat.y * quat.y;
  3958. var zz = quat.z * quat.z;
  3959. var xy = quat.x * quat.y;
  3960. var zw = quat.z * quat.w;
  3961. var zx = quat.z * quat.x;
  3962. var yw = quat.y * quat.w;
  3963. var yz = quat.y * quat.z;
  3964. var xw = quat.x * quat.w;
  3965. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3966. result.m[1] = 2.0 * (xy + zw);
  3967. result.m[2] = 2.0 * (zx - yw);
  3968. result.m[3] = 0.0;
  3969. result.m[4] = 2.0 * (xy - zw);
  3970. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3971. result.m[6] = 2.0 * (yz + xw);
  3972. result.m[7] = 0.0;
  3973. result.m[8] = 2.0 * (zx + yw);
  3974. result.m[9] = 2.0 * (yz - xw);
  3975. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3976. result.m[11] = 0.0;
  3977. result.m[12] = 0.0;
  3978. result.m[13] = 0.0;
  3979. result.m[14] = 0.0;
  3980. result.m[15] = 1.0;
  3981. result._markAsUpdated();
  3982. };
  3983. return Matrix;
  3984. }());
  3985. Matrix._tempQuaternion = new Quaternion();
  3986. Matrix._xAxis = Vector3.Zero();
  3987. Matrix._yAxis = Vector3.Zero();
  3988. Matrix._zAxis = Vector3.Zero();
  3989. Matrix._updateFlagSeed = 0;
  3990. BABYLON.Matrix = Matrix;
  3991. var Plane = (function () {
  3992. /**
  3993. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3994. */
  3995. function Plane(a, b, c, d) {
  3996. this.normal = new Vector3(a, b, c);
  3997. this.d = d;
  3998. }
  3999. /**
  4000. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4001. */
  4002. Plane.prototype.asArray = function () {
  4003. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4004. };
  4005. // Methods
  4006. /**
  4007. * Returns a new plane copied from the current Plane.
  4008. */
  4009. Plane.prototype.clone = function () {
  4010. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4011. };
  4012. /**
  4013. * Returns the string "Plane".
  4014. */
  4015. Plane.prototype.getClassName = function () {
  4016. return "Plane";
  4017. };
  4018. /**
  4019. * Returns the Plane hash code.
  4020. */
  4021. Plane.prototype.getHashCode = function () {
  4022. var hash = this.normal.getHashCode();
  4023. hash = (hash * 397) ^ (this.d || 0);
  4024. return hash;
  4025. };
  4026. /**
  4027. * Normalize the current Plane in place.
  4028. * Returns the updated Plane.
  4029. */
  4030. Plane.prototype.normalize = function () {
  4031. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4032. var magnitude = 0.0;
  4033. if (norm !== 0) {
  4034. magnitude = 1.0 / norm;
  4035. }
  4036. this.normal.x *= magnitude;
  4037. this.normal.y *= magnitude;
  4038. this.normal.z *= magnitude;
  4039. this.d *= magnitude;
  4040. return this;
  4041. };
  4042. /**
  4043. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4044. */
  4045. Plane.prototype.transform = function (transformation) {
  4046. var transposedMatrix = Matrix.Transpose(transformation);
  4047. var x = this.normal.x;
  4048. var y = this.normal.y;
  4049. var z = this.normal.z;
  4050. var d = this.d;
  4051. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4052. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4053. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4054. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4055. return new Plane(normalX, normalY, normalZ, finalD);
  4056. };
  4057. /**
  4058. * Returns the dot product (float) of the point coordinates and the plane normal.
  4059. */
  4060. Plane.prototype.dotCoordinate = function (point) {
  4061. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4062. };
  4063. /**
  4064. * Updates the current Plane from the plane defined by the three passed points.
  4065. * Returns the updated Plane.
  4066. */
  4067. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4068. var x1 = point2.x - point1.x;
  4069. var y1 = point2.y - point1.y;
  4070. var z1 = point2.z - point1.z;
  4071. var x2 = point3.x - point1.x;
  4072. var y2 = point3.y - point1.y;
  4073. var z2 = point3.z - point1.z;
  4074. var yz = (y1 * z2) - (z1 * y2);
  4075. var xz = (z1 * x2) - (x1 * z2);
  4076. var xy = (x1 * y2) - (y1 * x2);
  4077. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4078. var invPyth;
  4079. if (pyth !== 0) {
  4080. invPyth = 1.0 / pyth;
  4081. }
  4082. else {
  4083. invPyth = 0.0;
  4084. }
  4085. this.normal.x = yz * invPyth;
  4086. this.normal.y = xz * invPyth;
  4087. this.normal.z = xy * invPyth;
  4088. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4089. return this;
  4090. };
  4091. /**
  4092. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4093. */
  4094. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4095. var dot = Vector3.Dot(this.normal, direction);
  4096. return (dot <= epsilon);
  4097. };
  4098. /**
  4099. * Returns the signed distance (float) from the passed point to the Plane.
  4100. */
  4101. Plane.prototype.signedDistanceTo = function (point) {
  4102. return Vector3.Dot(point, this.normal) + this.d;
  4103. };
  4104. // Statics
  4105. /**
  4106. * Returns a new Plane from the passed array.
  4107. */
  4108. Plane.FromArray = function (array) {
  4109. return new Plane(array[0], array[1], array[2], array[3]);
  4110. };
  4111. /**
  4112. * Returns a new Plane defined by the three passed points.
  4113. */
  4114. Plane.FromPoints = function (point1, point2, point3) {
  4115. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4116. result.copyFromPoints(point1, point2, point3);
  4117. return result;
  4118. };
  4119. /**
  4120. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4121. * Note : the vector "normal" is updated because normalized.
  4122. */
  4123. Plane.FromPositionAndNormal = function (origin, normal) {
  4124. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4125. normal.normalize();
  4126. result.normal = normal;
  4127. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4128. return result;
  4129. };
  4130. /**
  4131. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4132. */
  4133. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4134. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4135. return Vector3.Dot(point, normal) + d;
  4136. };
  4137. return Plane;
  4138. }());
  4139. BABYLON.Plane = Plane;
  4140. var Viewport = (function () {
  4141. /**
  4142. * Creates a Viewport object located at (x, y) and sized (width, height).
  4143. */
  4144. function Viewport(x, y, width, height) {
  4145. this.x = x;
  4146. this.y = y;
  4147. this.width = width;
  4148. this.height = height;
  4149. }
  4150. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4151. if (renderWidthOrEngine.getRenderWidth) {
  4152. var engine = renderWidthOrEngine;
  4153. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4154. }
  4155. var renderWidth = renderWidthOrEngine;
  4156. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4157. };
  4158. /**
  4159. * Returns a new Viewport copied from the current one.
  4160. */
  4161. Viewport.prototype.clone = function () {
  4162. return new Viewport(this.x, this.y, this.width, this.height);
  4163. };
  4164. return Viewport;
  4165. }());
  4166. BABYLON.Viewport = Viewport;
  4167. var Frustum = (function () {
  4168. function Frustum() {
  4169. }
  4170. /**
  4171. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4172. */
  4173. Frustum.GetPlanes = function (transform) {
  4174. var frustumPlanes = [];
  4175. for (var index = 0; index < 6; index++) {
  4176. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4177. }
  4178. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4179. return frustumPlanes;
  4180. };
  4181. /**
  4182. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4183. */
  4184. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4185. // Near
  4186. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4187. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4188. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4189. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4190. frustumPlanes[0].normalize();
  4191. // Far
  4192. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4193. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4194. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4195. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4196. frustumPlanes[1].normalize();
  4197. // Left
  4198. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4199. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4200. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4201. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4202. frustumPlanes[2].normalize();
  4203. // Right
  4204. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4205. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4206. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4207. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4208. frustumPlanes[3].normalize();
  4209. // Top
  4210. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4211. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4212. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4213. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4214. frustumPlanes[4].normalize();
  4215. // Bottom
  4216. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4217. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4218. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4219. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4220. frustumPlanes[5].normalize();
  4221. };
  4222. return Frustum;
  4223. }());
  4224. BABYLON.Frustum = Frustum;
  4225. var Space;
  4226. (function (Space) {
  4227. Space[Space["LOCAL"] = 0] = "LOCAL";
  4228. Space[Space["WORLD"] = 1] = "WORLD";
  4229. Space[Space["BONE"] = 2] = "BONE";
  4230. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4231. var Axis = (function () {
  4232. function Axis() {
  4233. }
  4234. return Axis;
  4235. }());
  4236. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4237. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4238. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4239. BABYLON.Axis = Axis;
  4240. ;
  4241. var BezierCurve = (function () {
  4242. function BezierCurve() {
  4243. }
  4244. /**
  4245. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4246. */
  4247. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4248. // Extract X (which is equal to time here)
  4249. var f0 = 1 - 3 * x2 + 3 * x1;
  4250. var f1 = 3 * x2 - 6 * x1;
  4251. var f2 = 3 * x1;
  4252. var refinedT = t;
  4253. for (var i = 0; i < 5; i++) {
  4254. var refinedT2 = refinedT * refinedT;
  4255. var refinedT3 = refinedT2 * refinedT;
  4256. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4257. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4258. refinedT -= (x - t) * slope;
  4259. refinedT = Math.min(1, Math.max(0, refinedT));
  4260. }
  4261. // Resolve cubic bezier for the given x
  4262. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4263. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4264. Math.pow(refinedT, 3);
  4265. };
  4266. return BezierCurve;
  4267. }());
  4268. BABYLON.BezierCurve = BezierCurve;
  4269. var Orientation;
  4270. (function (Orientation) {
  4271. Orientation[Orientation["CW"] = 0] = "CW";
  4272. Orientation[Orientation["CCW"] = 1] = "CCW";
  4273. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4274. var Angle = (function () {
  4275. /**
  4276. * Creates an Angle object of "radians" radians (float).
  4277. */
  4278. function Angle(radians) {
  4279. var _this = this;
  4280. /**
  4281. * Returns the Angle value in degrees (float).
  4282. */
  4283. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4284. /**
  4285. * Returns the Angle value in radians (float).
  4286. */
  4287. this.radians = function () { return _this._radians; };
  4288. this._radians = radians;
  4289. if (this._radians < 0.0)
  4290. this._radians += (2.0 * Math.PI);
  4291. }
  4292. /**
  4293. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4294. */
  4295. Angle.BetweenTwoPoints = function (a, b) {
  4296. var delta = b.subtract(a);
  4297. var theta = Math.atan2(delta.y, delta.x);
  4298. return new Angle(theta);
  4299. };
  4300. /**
  4301. * Returns a new Angle object from the passed float in radians.
  4302. */
  4303. Angle.FromRadians = function (radians) {
  4304. return new Angle(radians);
  4305. };
  4306. /**
  4307. * Returns a new Angle object from the passed float in degrees.
  4308. */
  4309. Angle.FromDegrees = function (degrees) {
  4310. return new Angle(degrees * Math.PI / 180.0);
  4311. };
  4312. return Angle;
  4313. }());
  4314. BABYLON.Angle = Angle;
  4315. var Arc2 = (function () {
  4316. /**
  4317. * Creates an Arc object from the three passed points : start, middle and end.
  4318. */
  4319. function Arc2(startPoint, midPoint, endPoint) {
  4320. this.startPoint = startPoint;
  4321. this.midPoint = midPoint;
  4322. this.endPoint = endPoint;
  4323. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4324. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4325. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4326. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4327. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4328. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4329. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4330. var a1 = this.startAngle.degrees();
  4331. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4332. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4333. // angles correction
  4334. if (a2 - a1 > +180.0)
  4335. a2 -= 360.0;
  4336. if (a2 - a1 < -180.0)
  4337. a2 += 360.0;
  4338. if (a3 - a2 > +180.0)
  4339. a3 -= 360.0;
  4340. if (a3 - a2 < -180.0)
  4341. a3 += 360.0;
  4342. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4343. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4344. }
  4345. return Arc2;
  4346. }());
  4347. BABYLON.Arc2 = Arc2;
  4348. var Path2 = (function () {
  4349. /**
  4350. * Creates a Path2 object from the starting 2D coordinates x and y.
  4351. */
  4352. function Path2(x, y) {
  4353. this._points = new Array();
  4354. this._length = 0.0;
  4355. this.closed = false;
  4356. this._points.push(new Vector2(x, y));
  4357. }
  4358. /**
  4359. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4360. * Returns the updated Path2.
  4361. */
  4362. Path2.prototype.addLineTo = function (x, y) {
  4363. if (closed) {
  4364. //Tools.Error("cannot add lines to closed paths");
  4365. return this;
  4366. }
  4367. var newPoint = new Vector2(x, y);
  4368. var previousPoint = this._points[this._points.length - 1];
  4369. this._points.push(newPoint);
  4370. this._length += newPoint.subtract(previousPoint).length();
  4371. return this;
  4372. };
  4373. /**
  4374. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4375. * Returns the updated Path2.
  4376. */
  4377. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4378. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4379. if (closed) {
  4380. //Tools.Error("cannot add arcs to closed paths");
  4381. return this;
  4382. }
  4383. var startPoint = this._points[this._points.length - 1];
  4384. var midPoint = new Vector2(midX, midY);
  4385. var endPoint = new Vector2(endX, endY);
  4386. var arc = new Arc2(startPoint, midPoint, endPoint);
  4387. var increment = arc.angle.radians() / numberOfSegments;
  4388. if (arc.orientation === Orientation.CW)
  4389. increment *= -1;
  4390. var currentAngle = arc.startAngle.radians() + increment;
  4391. for (var i = 0; i < numberOfSegments; i++) {
  4392. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4393. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4394. this.addLineTo(x, y);
  4395. currentAngle += increment;
  4396. }
  4397. return this;
  4398. };
  4399. /**
  4400. * Closes the Path2.
  4401. * Returns the Path2.
  4402. */
  4403. Path2.prototype.close = function () {
  4404. this.closed = true;
  4405. return this;
  4406. };
  4407. /**
  4408. * Returns the Path2 total length (float).
  4409. */
  4410. Path2.prototype.length = function () {
  4411. var result = this._length;
  4412. if (!this.closed) {
  4413. var lastPoint = this._points[this._points.length - 1];
  4414. var firstPoint = this._points[0];
  4415. result += (firstPoint.subtract(lastPoint).length());
  4416. }
  4417. return result;
  4418. };
  4419. /**
  4420. * Returns the Path2 internal array of points.
  4421. */
  4422. Path2.prototype.getPoints = function () {
  4423. return this._points;
  4424. };
  4425. /**
  4426. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4427. */
  4428. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4429. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4430. //Tools.Error("normalized length position should be between 0 and 1.");
  4431. return Vector2.Zero();
  4432. }
  4433. var lengthPosition = normalizedLengthPosition * this.length();
  4434. var previousOffset = 0;
  4435. for (var i = 0; i < this._points.length; i++) {
  4436. var j = (i + 1) % this._points.length;
  4437. var a = this._points[i];
  4438. var b = this._points[j];
  4439. var bToA = b.subtract(a);
  4440. var nextOffset = (bToA.length() + previousOffset);
  4441. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4442. var dir = bToA.normalize();
  4443. var localOffset = lengthPosition - previousOffset;
  4444. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4445. }
  4446. previousOffset = nextOffset;
  4447. }
  4448. //Tools.Error("internal error");
  4449. return Vector2.Zero();
  4450. };
  4451. /**
  4452. * Returns a new Path2 starting at the coordinates (x, y).
  4453. */
  4454. Path2.StartingAt = function (x, y) {
  4455. return new Path2(x, y);
  4456. };
  4457. return Path2;
  4458. }());
  4459. BABYLON.Path2 = Path2;
  4460. var Path3D = (function () {
  4461. /**
  4462. * new Path3D(path, normal, raw)
  4463. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4464. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4465. * path : an array of Vector3, the curve axis of the Path3D
  4466. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4467. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4468. */
  4469. function Path3D(path, firstNormal, raw) {
  4470. this.path = path;
  4471. this._curve = new Array();
  4472. this._distances = new Array();
  4473. this._tangents = new Array();
  4474. this._normals = new Array();
  4475. this._binormals = new Array();
  4476. for (var p = 0; p < path.length; p++) {
  4477. this._curve[p] = path[p].clone(); // hard copy
  4478. }
  4479. this._raw = raw || false;
  4480. this._compute(firstNormal);
  4481. }
  4482. /**
  4483. * Returns the Path3D array of successive Vector3 designing its curve.
  4484. */
  4485. Path3D.prototype.getCurve = function () {
  4486. return this._curve;
  4487. };
  4488. /**
  4489. * Returns an array populated with tangent vectors on each Path3D curve point.
  4490. */
  4491. Path3D.prototype.getTangents = function () {
  4492. return this._tangents;
  4493. };
  4494. /**
  4495. * Returns an array populated with normal vectors on each Path3D curve point.
  4496. */
  4497. Path3D.prototype.getNormals = function () {
  4498. return this._normals;
  4499. };
  4500. /**
  4501. * Returns an array populated with binormal vectors on each Path3D curve point.
  4502. */
  4503. Path3D.prototype.getBinormals = function () {
  4504. return this._binormals;
  4505. };
  4506. /**
  4507. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4508. */
  4509. Path3D.prototype.getDistances = function () {
  4510. return this._distances;
  4511. };
  4512. /**
  4513. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4514. * Returns the same object updated.
  4515. */
  4516. Path3D.prototype.update = function (path, firstNormal) {
  4517. for (var p = 0; p < path.length; p++) {
  4518. this._curve[p].x = path[p].x;
  4519. this._curve[p].y = path[p].y;
  4520. this._curve[p].z = path[p].z;
  4521. }
  4522. this._compute(firstNormal);
  4523. return this;
  4524. };
  4525. // private function compute() : computes tangents, normals and binormals
  4526. Path3D.prototype._compute = function (firstNormal) {
  4527. var l = this._curve.length;
  4528. // first and last tangents
  4529. this._tangents[0] = this._getFirstNonNullVector(0);
  4530. if (!this._raw) {
  4531. this._tangents[0].normalize();
  4532. }
  4533. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4534. if (!this._raw) {
  4535. this._tangents[l - 1].normalize();
  4536. }
  4537. // normals and binormals at first point : arbitrary vector with _normalVector()
  4538. var tg0 = this._tangents[0];
  4539. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4540. this._normals[0] = pp0;
  4541. if (!this._raw) {
  4542. this._normals[0].normalize();
  4543. }
  4544. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4545. if (!this._raw) {
  4546. this._binormals[0].normalize();
  4547. }
  4548. this._distances[0] = 0.0;
  4549. // normals and binormals : next points
  4550. var prev; // previous vector (segment)
  4551. var cur; // current vector (segment)
  4552. var curTang; // current tangent
  4553. // previous normal
  4554. var prevBinor; // previous binormal
  4555. for (var i = 1; i < l; i++) {
  4556. // tangents
  4557. prev = this._getLastNonNullVector(i);
  4558. if (i < l - 1) {
  4559. cur = this._getFirstNonNullVector(i);
  4560. this._tangents[i] = prev.add(cur);
  4561. this._tangents[i].normalize();
  4562. }
  4563. this._distances[i] = this._distances[i - 1] + prev.length();
  4564. // normals and binormals
  4565. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4566. curTang = this._tangents[i];
  4567. prevBinor = this._binormals[i - 1];
  4568. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4569. if (!this._raw) {
  4570. this._normals[i].normalize();
  4571. }
  4572. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4573. if (!this._raw) {
  4574. this._binormals[i].normalize();
  4575. }
  4576. }
  4577. };
  4578. // private function getFirstNonNullVector(index)
  4579. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4580. Path3D.prototype._getFirstNonNullVector = function (index) {
  4581. var i = 1;
  4582. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4583. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4584. i++;
  4585. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4586. }
  4587. return nNVector;
  4588. };
  4589. // private function getLastNonNullVector(index)
  4590. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4591. Path3D.prototype._getLastNonNullVector = function (index) {
  4592. var i = 1;
  4593. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4594. while (nLVector.length() === 0 && index > i + 1) {
  4595. i++;
  4596. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4597. }
  4598. return nLVector;
  4599. };
  4600. // private function normalVector(v0, vt, va) :
  4601. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4602. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4603. Path3D.prototype._normalVector = function (v0, vt, va) {
  4604. var normal0;
  4605. var tgl = vt.length();
  4606. if (tgl === 0.0) {
  4607. tgl = 1.0;
  4608. }
  4609. if (va === undefined || va === null) {
  4610. var point;
  4611. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4612. point = new Vector3(0.0, -1.0, 0.0);
  4613. }
  4614. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4615. point = new Vector3(1.0, 0.0, 0.0);
  4616. }
  4617. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4618. point = new Vector3(0.0, 0.0, 1.0);
  4619. }
  4620. normal0 = Vector3.Cross(vt, point);
  4621. }
  4622. else {
  4623. normal0 = Vector3.Cross(vt, va);
  4624. Vector3.CrossToRef(normal0, vt, normal0);
  4625. }
  4626. normal0.normalize();
  4627. return normal0;
  4628. };
  4629. return Path3D;
  4630. }());
  4631. BABYLON.Path3D = Path3D;
  4632. var Curve3 = (function () {
  4633. /**
  4634. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4635. * A Curve3 is designed from a series of successive Vector3.
  4636. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4637. */
  4638. function Curve3(points) {
  4639. this._length = 0.0;
  4640. this._points = points;
  4641. this._length = this._computeLength(points);
  4642. }
  4643. /**
  4644. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4645. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4646. * @param v1 (Vector3) the control point
  4647. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4648. * @param nbPoints (integer) the wanted number of points in the curve
  4649. */
  4650. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4651. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4652. var bez = new Array();
  4653. var equation = function (t, val0, val1, val2) {
  4654. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4655. return res;
  4656. };
  4657. for (var i = 0; i <= nbPoints; i++) {
  4658. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  4659. }
  4660. return new Curve3(bez);
  4661. };
  4662. /**
  4663. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4664. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4665. * @param v1 (Vector3) the first control point
  4666. * @param v2 (Vector3) the second control point
  4667. * @param v3 (Vector3) the end point of the Cubic Bezier
  4668. * @param nbPoints (integer) the wanted number of points in the curve
  4669. */
  4670. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4671. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4672. var bez = new Array();
  4673. var equation = function (t, val0, val1, val2, val3) {
  4674. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4675. return res;
  4676. };
  4677. for (var i = 0; i <= nbPoints; i++) {
  4678. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  4679. }
  4680. return new Curve3(bez);
  4681. };
  4682. /**
  4683. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4684. * @param p1 (Vector3) the origin point of the Hermite Spline
  4685. * @param t1 (Vector3) the tangent vector at the origin point
  4686. * @param p2 (Vector3) the end point of the Hermite Spline
  4687. * @param t2 (Vector3) the tangent vector at the end point
  4688. * @param nbPoints (integer) the wanted number of points in the curve
  4689. */
  4690. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4691. var hermite = new Array();
  4692. var step = 1.0 / nbPoints;
  4693. for (var i = 0; i <= nbPoints; i++) {
  4694. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4695. }
  4696. return new Curve3(hermite);
  4697. };
  4698. /**
  4699. * Returns a Curve3 object along a CatmullRom Spline curve :
  4700. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4701. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4702. */
  4703. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4704. var totalPoints = new Array();
  4705. totalPoints.push(points[0].clone());
  4706. Array.prototype.push.apply(totalPoints, points);
  4707. totalPoints.push(points[points.length - 1].clone());
  4708. var catmullRom = new Array();
  4709. var step = 1.0 / nbPoints;
  4710. for (var i = 0; i < totalPoints.length - 3; i++) {
  4711. var amount = 0.0;
  4712. for (var c = 0; c < nbPoints; c++) {
  4713. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4714. amount += step;
  4715. }
  4716. }
  4717. i--;
  4718. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4719. return new Curve3(catmullRom);
  4720. };
  4721. /**
  4722. * Returns the Curve3 stored array of successive Vector3
  4723. */
  4724. Curve3.prototype.getPoints = function () {
  4725. return this._points;
  4726. };
  4727. /**
  4728. * Returns the computed length (float) of the curve.
  4729. */
  4730. Curve3.prototype.length = function () {
  4731. return this._length;
  4732. };
  4733. /**
  4734. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4735. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4736. * curveA and curveB keep unchanged.
  4737. */
  4738. Curve3.prototype.continue = function (curve) {
  4739. var lastPoint = this._points[this._points.length - 1];
  4740. var continuedPoints = this._points.slice();
  4741. var curvePoints = curve.getPoints();
  4742. for (var i = 1; i < curvePoints.length; i++) {
  4743. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4744. }
  4745. var continuedCurve = new Curve3(continuedPoints);
  4746. return continuedCurve;
  4747. };
  4748. Curve3.prototype._computeLength = function (path) {
  4749. var l = 0;
  4750. for (var i = 1; i < path.length; i++) {
  4751. l += (path[i].subtract(path[i - 1])).length();
  4752. }
  4753. return l;
  4754. };
  4755. return Curve3;
  4756. }());
  4757. BABYLON.Curve3 = Curve3;
  4758. // Vertex formats
  4759. var PositionNormalVertex = (function () {
  4760. function PositionNormalVertex(position, normal) {
  4761. if (position === void 0) { position = Vector3.Zero(); }
  4762. if (normal === void 0) { normal = Vector3.Up(); }
  4763. this.position = position;
  4764. this.normal = normal;
  4765. }
  4766. PositionNormalVertex.prototype.clone = function () {
  4767. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4768. };
  4769. return PositionNormalVertex;
  4770. }());
  4771. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4772. var PositionNormalTextureVertex = (function () {
  4773. function PositionNormalTextureVertex(position, normal, uv) {
  4774. if (position === void 0) { position = Vector3.Zero(); }
  4775. if (normal === void 0) { normal = Vector3.Up(); }
  4776. if (uv === void 0) { uv = Vector2.Zero(); }
  4777. this.position = position;
  4778. this.normal = normal;
  4779. this.uv = uv;
  4780. }
  4781. PositionNormalTextureVertex.prototype.clone = function () {
  4782. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4783. };
  4784. return PositionNormalTextureVertex;
  4785. }());
  4786. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4787. // Temporary pre-allocated objects for engine internal use
  4788. // usage in any internal function :
  4789. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4790. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4791. var Tmp = (function () {
  4792. function Tmp() {
  4793. }
  4794. return Tmp;
  4795. }());
  4796. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4797. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4798. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4799. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4800. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4801. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4802. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4803. Matrix.Zero(), Matrix.Zero(),
  4804. Matrix.Zero(), Matrix.Zero(),
  4805. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4806. BABYLON.Tmp = Tmp;
  4807. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4808. var MathTmp = (function () {
  4809. function MathTmp() {
  4810. }
  4811. return MathTmp;
  4812. }());
  4813. MathTmp.Vector3 = [Vector3.Zero()];
  4814. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4815. MathTmp.Quaternion = [Quaternion.Zero()];
  4816. })(BABYLON || (BABYLON = {}));
  4817. //# sourceMappingURL=babylon.math.js.map
  4818. var BABYLON;
  4819. (function (BABYLON) {
  4820. var Scalar = (function () {
  4821. function Scalar() {
  4822. }
  4823. /**
  4824. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4825. */
  4826. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4827. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4828. var num = a - b;
  4829. return -epsilon <= num && num <= epsilon;
  4830. };
  4831. /**
  4832. * Returns a string : the upper case translation of the number i to hexadecimal.
  4833. */
  4834. Scalar.ToHex = function (i) {
  4835. var str = i.toString(16);
  4836. if (i <= 15) {
  4837. return ("0" + str).toUpperCase();
  4838. }
  4839. return str.toUpperCase();
  4840. };
  4841. /**
  4842. * Returns -1 if value is negative and +1 is value is positive.
  4843. * Returns the value itself if it's equal to zero.
  4844. */
  4845. Scalar.Sign = function (value) {
  4846. value = +value; // convert to a number
  4847. if (value === 0 || isNaN(value))
  4848. return value;
  4849. return value > 0 ? 1 : -1;
  4850. };
  4851. /**
  4852. * Returns the value itself if it's between min and max.
  4853. * Returns min if the value is lower than min.
  4854. * Returns max if the value is greater than max.
  4855. */
  4856. Scalar.Clamp = function (value, min, max) {
  4857. if (min === void 0) { min = 0; }
  4858. if (max === void 0) { max = 1; }
  4859. return Math.min(max, Math.max(min, value));
  4860. };
  4861. /**
  4862. * Returns the log2 of value.
  4863. */
  4864. Scalar.Log2 = function (value) {
  4865. return Math.log(value) * Math.LOG2E;
  4866. };
  4867. /**
  4868. * Loops the value, so that it is never larger than length and never smaller than 0.
  4869. *
  4870. * This is similar to the modulo operator but it works with floating point numbers.
  4871. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4872. * With t = 5 and length = 2.5, the result would be 0.0.
  4873. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4874. */
  4875. Scalar.Repeat = function (value, length) {
  4876. return value - Math.floor(value / length) * length;
  4877. };
  4878. /**
  4879. * Normalize the value between 0.0 and 1.0 using min and max values
  4880. */
  4881. Scalar.Normalize = function (value, min, max) {
  4882. return (value - min) / (max - min);
  4883. };
  4884. /**
  4885. * Denormalize the value from 0.0 and 1.0 using min and max values
  4886. */
  4887. Scalar.Denormalize = function (normalized, min, max) {
  4888. return (normalized * (max - min) + min);
  4889. };
  4890. /**
  4891. * Calculates the shortest difference between two given angles given in degrees.
  4892. */
  4893. Scalar.DeltaAngle = function (current, target) {
  4894. var num = Scalar.Repeat(target - current, 360.0);
  4895. if (num > 180.0) {
  4896. num -= 360.0;
  4897. }
  4898. return num;
  4899. };
  4900. /**
  4901. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4902. *
  4903. * The returned value will move back and forth between 0 and length
  4904. */
  4905. Scalar.PingPong = function (tx, length) {
  4906. var t = Scalar.Repeat(tx, length * 2.0);
  4907. return length - Math.abs(t - length);
  4908. };
  4909. /**
  4910. * Interpolates between min and max with smoothing at the limits.
  4911. *
  4912. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4913. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4914. */
  4915. Scalar.SmoothStep = function (from, to, tx) {
  4916. var t = Scalar.Clamp(tx);
  4917. t = -2.0 * t * t * t + 3.0 * t * t;
  4918. return to * t + from * (1.0 - t);
  4919. };
  4920. /**
  4921. * Moves a value current towards target.
  4922. *
  4923. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4924. * Negative values of maxDelta pushes the value away from target.
  4925. */
  4926. Scalar.MoveTowards = function (current, target, maxDelta) {
  4927. var result = 0;
  4928. if (Math.abs(target - current) <= maxDelta) {
  4929. result = target;
  4930. }
  4931. else {
  4932. result = current + Scalar.Sign(target - current) * maxDelta;
  4933. }
  4934. return result;
  4935. };
  4936. /**
  4937. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4938. *
  4939. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4940. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4941. */
  4942. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4943. var num = Scalar.DeltaAngle(current, target);
  4944. var result = 0;
  4945. if (-maxDelta < num && num < maxDelta) {
  4946. result = target;
  4947. }
  4948. else {
  4949. target = current + num;
  4950. result = Scalar.MoveTowards(current, target, maxDelta);
  4951. }
  4952. return result;
  4953. };
  4954. /**
  4955. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4956. */
  4957. Scalar.Lerp = function (start, end, amount) {
  4958. return start + ((end - start) * amount);
  4959. };
  4960. /**
  4961. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4962. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4963. */
  4964. Scalar.LerpAngle = function (start, end, amount) {
  4965. var num = Scalar.Repeat(end - start, 360.0);
  4966. if (num > 180.0) {
  4967. num -= 360.0;
  4968. }
  4969. return start + num * Scalar.Clamp(amount);
  4970. };
  4971. /**
  4972. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4973. */
  4974. Scalar.InverseLerp = function (a, b, value) {
  4975. var result = 0;
  4976. if (a != b) {
  4977. result = Scalar.Clamp((value - a) / (b - a));
  4978. }
  4979. else {
  4980. result = 0.0;
  4981. }
  4982. return result;
  4983. };
  4984. /**
  4985. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4986. */
  4987. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4988. var squared = amount * amount;
  4989. var cubed = amount * squared;
  4990. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4991. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4992. var part3 = (cubed - (2.0 * squared)) + amount;
  4993. var part4 = cubed - squared;
  4994. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4995. };
  4996. /**
  4997. * Returns a random float number between and min and max values
  4998. */
  4999. Scalar.RandomRange = function (min, max) {
  5000. if (min === max)
  5001. return min;
  5002. return ((Math.random() * (max - min)) + min);
  5003. };
  5004. /**
  5005. * This function returns percentage of a number in a given range.
  5006. *
  5007. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5008. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5009. */
  5010. Scalar.RangeToPercent = function (number, min, max) {
  5011. return ((number - min) / (max - min));
  5012. };
  5013. /**
  5014. * This function returns number that corresponds to the percentage in a given range.
  5015. *
  5016. * PercentToRange(0.34,0,100) will return 34.
  5017. */
  5018. Scalar.PercentToRange = function (percent, min, max) {
  5019. return ((max - min) * percent + min);
  5020. };
  5021. return Scalar;
  5022. }());
  5023. BABYLON.Scalar = Scalar;
  5024. })(BABYLON || (BABYLON = {}));
  5025. //# sourceMappingURL=babylon.math.scalar.js.map
  5026. //# sourceMappingURL=babylon.mixins.js.map
  5027. var BABYLON;
  5028. (function (BABYLON) {
  5029. var __decoratorInitialStore = {};
  5030. var __mergedStore = {};
  5031. var _copySource = function (creationFunction, source, instanciate) {
  5032. var destination = creationFunction();
  5033. // Tags
  5034. if (BABYLON.Tags) {
  5035. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5036. }
  5037. var classStore = getMergedStore(destination);
  5038. // Properties
  5039. for (var property in classStore) {
  5040. var propertyDescriptor = classStore[property];
  5041. var sourceProperty = source[property];
  5042. var propertyType = propertyDescriptor.type;
  5043. if (sourceProperty !== undefined && sourceProperty !== null) {
  5044. switch (propertyType) {
  5045. case 0: // Value
  5046. case 6:
  5047. destination[property] = sourceProperty;
  5048. break;
  5049. case 1: // Texture
  5050. case 2: // Color3
  5051. case 3: // FresnelParameters
  5052. case 4: // Vector2
  5053. case 5: // Vector3
  5054. case 7:
  5055. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5056. break;
  5057. }
  5058. }
  5059. }
  5060. return destination;
  5061. };
  5062. function getDirectStore(target) {
  5063. var classKey = target.getClassName();
  5064. if (!__decoratorInitialStore[classKey]) {
  5065. __decoratorInitialStore[classKey] = {};
  5066. }
  5067. return __decoratorInitialStore[classKey];
  5068. }
  5069. /**
  5070. * Return the list of properties flagged as serializable
  5071. * @param target: host object
  5072. */
  5073. function getMergedStore(target) {
  5074. var classKey = target.getClassName();
  5075. if (__mergedStore[classKey]) {
  5076. return __mergedStore[classKey];
  5077. }
  5078. __mergedStore[classKey] = {};
  5079. var store = __mergedStore[classKey];
  5080. var currentTarget = target;
  5081. var currentKey = classKey;
  5082. while (currentKey) {
  5083. var initialStore = __decoratorInitialStore[currentKey];
  5084. for (var property in initialStore) {
  5085. store[property] = initialStore[property];
  5086. }
  5087. var parent_1 = void 0;
  5088. var done = false;
  5089. do {
  5090. parent_1 = Object.getPrototypeOf(currentTarget);
  5091. if (!parent_1.getClassName) {
  5092. done = true;
  5093. break;
  5094. }
  5095. if (parent_1.getClassName() !== currentKey) {
  5096. break;
  5097. }
  5098. currentTarget = parent_1;
  5099. } while (parent_1);
  5100. if (done) {
  5101. break;
  5102. }
  5103. currentKey = parent_1.getClassName();
  5104. currentTarget = parent_1;
  5105. }
  5106. return store;
  5107. }
  5108. function generateSerializableMember(type, sourceName) {
  5109. return function (target, propertyKey) {
  5110. var classStore = getDirectStore(target);
  5111. if (!classStore[propertyKey]) {
  5112. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5113. }
  5114. };
  5115. }
  5116. function generateExpandMember(setCallback, targetKey) {
  5117. return function (target, propertyKey) {
  5118. var key = targetKey || ("_" + propertyKey);
  5119. Object.defineProperty(target, propertyKey, {
  5120. get: function () {
  5121. return this[key];
  5122. },
  5123. set: function (value) {
  5124. if (this[key] === value) {
  5125. return;
  5126. }
  5127. this[key] = value;
  5128. target[setCallback].apply(this);
  5129. },
  5130. enumerable: true,
  5131. configurable: true
  5132. });
  5133. };
  5134. }
  5135. function expandToProperty(callback, targetKey) {
  5136. return generateExpandMember(callback, targetKey);
  5137. }
  5138. BABYLON.expandToProperty = expandToProperty;
  5139. function serialize(sourceName) {
  5140. return generateSerializableMember(0, sourceName); // value member
  5141. }
  5142. BABYLON.serialize = serialize;
  5143. function serializeAsTexture(sourceName) {
  5144. return generateSerializableMember(1, sourceName); // texture member
  5145. }
  5146. BABYLON.serializeAsTexture = serializeAsTexture;
  5147. function serializeAsColor3(sourceName) {
  5148. return generateSerializableMember(2, sourceName); // color3 member
  5149. }
  5150. BABYLON.serializeAsColor3 = serializeAsColor3;
  5151. function serializeAsFresnelParameters(sourceName) {
  5152. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5153. }
  5154. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5155. function serializeAsVector2(sourceName) {
  5156. return generateSerializableMember(4, sourceName); // vector2 member
  5157. }
  5158. BABYLON.serializeAsVector2 = serializeAsVector2;
  5159. function serializeAsVector3(sourceName) {
  5160. return generateSerializableMember(5, sourceName); // vector3 member
  5161. }
  5162. BABYLON.serializeAsVector3 = serializeAsVector3;
  5163. function serializeAsMeshReference(sourceName) {
  5164. return generateSerializableMember(6, sourceName); // mesh reference member
  5165. }
  5166. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5167. function serializeAsColorCurves(sourceName) {
  5168. return generateSerializableMember(7, sourceName); // color curves
  5169. }
  5170. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5171. function serializeAsColor4(sourceName) {
  5172. return generateSerializableMember(8, sourceName); // color 4
  5173. }
  5174. BABYLON.serializeAsColor4 = serializeAsColor4;
  5175. function serializeAsImageProcessingConfiguration(sourceName) {
  5176. return generateSerializableMember(9, sourceName); // image processing
  5177. }
  5178. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5179. var SerializationHelper = (function () {
  5180. function SerializationHelper() {
  5181. }
  5182. SerializationHelper.Serialize = function (entity, serializationObject) {
  5183. if (!serializationObject) {
  5184. serializationObject = {};
  5185. }
  5186. // Tags
  5187. if (BABYLON.Tags) {
  5188. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5189. }
  5190. var serializedProperties = getMergedStore(entity);
  5191. // Properties
  5192. for (var property in serializedProperties) {
  5193. var propertyDescriptor = serializedProperties[property];
  5194. var targetPropertyName = propertyDescriptor.sourceName || property;
  5195. var propertyType = propertyDescriptor.type;
  5196. var sourceProperty = entity[property];
  5197. if (sourceProperty !== undefined && sourceProperty !== null) {
  5198. switch (propertyType) {
  5199. case 0:
  5200. serializationObject[targetPropertyName] = sourceProperty;
  5201. break;
  5202. case 1:
  5203. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5204. break;
  5205. case 2:
  5206. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5207. break;
  5208. case 3:
  5209. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5210. break;
  5211. case 4:
  5212. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5213. break;
  5214. case 5:
  5215. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5216. break;
  5217. case 6:
  5218. serializationObject[targetPropertyName] = sourceProperty.id;
  5219. break;
  5220. case 7:
  5221. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5222. break;
  5223. case 8:
  5224. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5225. break;
  5226. case 9:
  5227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5228. break;
  5229. }
  5230. }
  5231. }
  5232. return serializationObject;
  5233. };
  5234. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5235. var destination = creationFunction();
  5236. // Tags
  5237. if (BABYLON.Tags) {
  5238. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5239. }
  5240. var classStore = getMergedStore(destination);
  5241. // Properties
  5242. for (var property in classStore) {
  5243. var propertyDescriptor = classStore[property];
  5244. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5245. var propertyType = propertyDescriptor.type;
  5246. if (sourceProperty !== undefined && sourceProperty !== null) {
  5247. switch (propertyType) {
  5248. case 0:
  5249. destination[property] = sourceProperty;
  5250. break;
  5251. case 1:
  5252. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5253. break;
  5254. case 2:
  5255. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5256. break;
  5257. case 3:
  5258. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5259. break;
  5260. case 4:
  5261. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5262. break;
  5263. case 5:
  5264. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5265. break;
  5266. case 6:
  5267. destination[property] = scene.getLastMeshByID(sourceProperty);
  5268. break;
  5269. case 7:
  5270. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5271. break;
  5272. case 8:
  5273. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5274. break;
  5275. case 9:
  5276. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5277. break;
  5278. }
  5279. }
  5280. }
  5281. return destination;
  5282. };
  5283. SerializationHelper.Clone = function (creationFunction, source) {
  5284. return _copySource(creationFunction, source, false);
  5285. };
  5286. SerializationHelper.Instanciate = function (creationFunction, source) {
  5287. return _copySource(creationFunction, source, true);
  5288. };
  5289. return SerializationHelper;
  5290. }());
  5291. BABYLON.SerializationHelper = SerializationHelper;
  5292. })(BABYLON || (BABYLON = {}));
  5293. //# sourceMappingURL=babylon.decorators.js.map
  5294. var BABYLON;
  5295. (function (BABYLON) {
  5296. /**
  5297. * A class serves as a medium between the observable and its observers
  5298. */
  5299. var EventState = (function () {
  5300. /**
  5301. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5302. */
  5303. function EventState(mask, skipNextObservers) {
  5304. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5305. this.initalize(mask, skipNextObservers);
  5306. }
  5307. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5308. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5309. this.mask = mask;
  5310. this.skipNextObservers = skipNextObservers;
  5311. return this;
  5312. };
  5313. return EventState;
  5314. }());
  5315. BABYLON.EventState = EventState;
  5316. /**
  5317. * Represent an Observer registered to a given Observable object.
  5318. */
  5319. var Observer = (function () {
  5320. function Observer(callback, mask) {
  5321. this.callback = callback;
  5322. this.mask = mask;
  5323. }
  5324. return Observer;
  5325. }());
  5326. BABYLON.Observer = Observer;
  5327. /**
  5328. * The Observable class is a simple implementation of the Observable pattern.
  5329. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  5330. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5331. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  5332. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  5333. */
  5334. var Observable = (function () {
  5335. function Observable(onObserverAdded) {
  5336. this._observers = new Array();
  5337. this._eventState = new EventState(0);
  5338. this._onObserverAdded = onObserverAdded;
  5339. }
  5340. /**
  5341. * Create a new Observer with the specified callback
  5342. * @param callback the callback that will be executed for that Observer
  5343. * @param mask the mask used to filter observers
  5344. * @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.
  5345. */
  5346. Observable.prototype.add = function (callback, mask, insertFirst) {
  5347. if (mask === void 0) { mask = -1; }
  5348. if (insertFirst === void 0) { insertFirst = false; }
  5349. if (!callback) {
  5350. return null;
  5351. }
  5352. var observer = new Observer(callback, mask);
  5353. if (insertFirst) {
  5354. this._observers.unshift(observer);
  5355. }
  5356. else {
  5357. this._observers.push(observer);
  5358. }
  5359. if (this._onObserverAdded) {
  5360. this._onObserverAdded(observer);
  5361. }
  5362. return observer;
  5363. };
  5364. /**
  5365. * Remove an Observer from the Observable object
  5366. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5367. */
  5368. Observable.prototype.remove = function (observer) {
  5369. var index = this._observers.indexOf(observer);
  5370. if (index !== -1) {
  5371. this._observers.splice(index, 1);
  5372. return true;
  5373. }
  5374. return false;
  5375. };
  5376. /**
  5377. * Remove a callback from the Observable object
  5378. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5379. */
  5380. Observable.prototype.removeCallback = function (callback) {
  5381. for (var index = 0; index < this._observers.length; index++) {
  5382. if (this._observers[index].callback === callback) {
  5383. this._observers.splice(index, 1);
  5384. return true;
  5385. }
  5386. }
  5387. return false;
  5388. };
  5389. /**
  5390. * Notify all Observers by calling their respective callback with the given data
  5391. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5392. * @param eventData
  5393. * @param mask
  5394. */
  5395. Observable.prototype.notifyObservers = function (eventData, mask) {
  5396. if (mask === void 0) { mask = -1; }
  5397. var state = this._eventState;
  5398. state.mask = mask;
  5399. state.skipNextObservers = false;
  5400. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5401. var obs = _a[_i];
  5402. if (obs.mask & mask) {
  5403. obs.callback(eventData, state);
  5404. }
  5405. if (state.skipNextObservers) {
  5406. return false;
  5407. }
  5408. }
  5409. return true;
  5410. };
  5411. /**
  5412. * Notify a specific observer
  5413. * @param eventData
  5414. * @param mask
  5415. */
  5416. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5417. if (mask === void 0) { mask = -1; }
  5418. var state = this._eventState;
  5419. state.mask = mask;
  5420. state.skipNextObservers = false;
  5421. observer.callback(eventData, state);
  5422. };
  5423. /**
  5424. * return true is the Observable has at least one Observer registered
  5425. */
  5426. Observable.prototype.hasObservers = function () {
  5427. return this._observers.length > 0;
  5428. };
  5429. /**
  5430. * Clear the list of observers
  5431. */
  5432. Observable.prototype.clear = function () {
  5433. this._observers = new Array();
  5434. this._onObserverAdded = null;
  5435. };
  5436. /**
  5437. * Clone the current observable
  5438. */
  5439. Observable.prototype.clone = function () {
  5440. var result = new Observable();
  5441. result._observers = this._observers.slice(0);
  5442. return result;
  5443. };
  5444. /**
  5445. * Does this observable handles observer registered with a given mask
  5446. * @param {number} trigger - the mask to be tested
  5447. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5448. **/
  5449. Observable.prototype.hasSpecificMask = function (mask) {
  5450. if (mask === void 0) { mask = -1; }
  5451. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5452. var obs = _a[_i];
  5453. if (obs.mask & mask || obs.mask === mask) {
  5454. return true;
  5455. }
  5456. }
  5457. return false;
  5458. };
  5459. return Observable;
  5460. }());
  5461. BABYLON.Observable = Observable;
  5462. })(BABYLON || (BABYLON = {}));
  5463. //# sourceMappingURL=babylon.observable.js.map
  5464. var BABYLON;
  5465. (function (BABYLON) {
  5466. var SmartArray = (function () {
  5467. function SmartArray(capacity) {
  5468. this.length = 0;
  5469. this._duplicateId = 0;
  5470. this.data = new Array(capacity);
  5471. this._id = SmartArray._GlobalId++;
  5472. }
  5473. SmartArray.prototype.push = function (value) {
  5474. this.data[this.length++] = value;
  5475. if (this.length > this.data.length) {
  5476. this.data.length *= 2;
  5477. }
  5478. if (!value.__smartArrayFlags) {
  5479. value.__smartArrayFlags = {};
  5480. }
  5481. value.__smartArrayFlags[this._id] = this._duplicateId;
  5482. };
  5483. SmartArray.prototype.forEach = function (func) {
  5484. for (var index = 0; index < this.length; index++) {
  5485. func(this.data[index]);
  5486. }
  5487. };
  5488. SmartArray.prototype.pushNoDuplicate = function (value) {
  5489. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5490. return false;
  5491. }
  5492. this.push(value);
  5493. return true;
  5494. };
  5495. SmartArray.prototype.sort = function (compareFn) {
  5496. this.data.sort(compareFn);
  5497. };
  5498. SmartArray.prototype.reset = function () {
  5499. this.length = 0;
  5500. this._duplicateId++;
  5501. };
  5502. SmartArray.prototype.dispose = function () {
  5503. this.reset();
  5504. if (this.data) {
  5505. this.data.length = 0;
  5506. this.data = null;
  5507. }
  5508. };
  5509. SmartArray.prototype.concat = function (array) {
  5510. if (array.length === 0) {
  5511. return;
  5512. }
  5513. if (this.length + array.length > this.data.length) {
  5514. this.data.length = (this.length + array.length) * 2;
  5515. }
  5516. for (var index = 0; index < array.length; index++) {
  5517. this.data[this.length++] = (array.data || array)[index];
  5518. }
  5519. };
  5520. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5521. if (array.length === 0) {
  5522. return;
  5523. }
  5524. if (this.length + array.length > this.data.length) {
  5525. this.data.length = (this.length + array.length) * 2;
  5526. }
  5527. for (var index = 0; index < array.length; index++) {
  5528. var item = (array.data || array)[index];
  5529. this.pushNoDuplicate(item);
  5530. }
  5531. };
  5532. SmartArray.prototype.indexOf = function (value) {
  5533. var position = this.data.indexOf(value);
  5534. if (position >= this.length) {
  5535. return -1;
  5536. }
  5537. return position;
  5538. };
  5539. SmartArray.prototype.contains = function (value) {
  5540. return this.data.indexOf(value) !== -1;
  5541. };
  5542. return SmartArray;
  5543. }());
  5544. // Statics
  5545. SmartArray._GlobalId = 0;
  5546. BABYLON.SmartArray = SmartArray;
  5547. })(BABYLON || (BABYLON = {}));
  5548. //# sourceMappingURL=babylon.smartArray.js.map
  5549. var BABYLON;
  5550. (function (BABYLON) {
  5551. // Screenshots
  5552. var screenshotCanvas;
  5553. var cloneValue = function (source, destinationObject) {
  5554. if (!source)
  5555. return null;
  5556. if (source instanceof BABYLON.Mesh) {
  5557. return null;
  5558. }
  5559. if (source instanceof BABYLON.SubMesh) {
  5560. return source.clone(destinationObject);
  5561. }
  5562. else if (source.clone) {
  5563. return source.clone();
  5564. }
  5565. return null;
  5566. };
  5567. var Tools = (function () {
  5568. function Tools() {
  5569. }
  5570. ;
  5571. /**
  5572. * Interpolates between a and b via alpha
  5573. * @param a The lower value (returned when alpha = 0)
  5574. * @param b The upper value (returned when alpha = 1)
  5575. * @param alpha The interpolation-factor
  5576. * @return The mixed value
  5577. */
  5578. Tools.Mix = function (a, b, alpha) {
  5579. return a * (1 - alpha) + b * alpha;
  5580. };
  5581. Tools.Instantiate = function (className) {
  5582. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5583. return Tools.RegisteredExternalClasses[className];
  5584. }
  5585. var arr = className.split(".");
  5586. var fn = (window || this);
  5587. for (var i = 0, len = arr.length; i < len; i++) {
  5588. fn = fn[arr[i]];
  5589. }
  5590. if (typeof fn !== "function") {
  5591. return null;
  5592. }
  5593. return fn;
  5594. };
  5595. Tools.SetImmediate = function (action) {
  5596. if (window.setImmediate) {
  5597. window.setImmediate(action);
  5598. }
  5599. else {
  5600. setTimeout(action, 1);
  5601. }
  5602. };
  5603. Tools.IsExponentOfTwo = function (value) {
  5604. var count = 1;
  5605. do {
  5606. count *= 2;
  5607. } while (count < value);
  5608. return count === value;
  5609. };
  5610. /**
  5611. * Find the next highest power of two.
  5612. * @param x Number to start search from.
  5613. * @return Next highest power of two.
  5614. */
  5615. Tools.CeilingPOT = function (x) {
  5616. x--;
  5617. x |= x >> 1;
  5618. x |= x >> 2;
  5619. x |= x >> 4;
  5620. x |= x >> 8;
  5621. x |= x >> 16;
  5622. x++;
  5623. return x;
  5624. };
  5625. /**
  5626. * Find the next lowest power of two.
  5627. * @param x Number to start search from.
  5628. * @return Next lowest power of two.
  5629. */
  5630. Tools.FloorPOT = function (x) {
  5631. x = x | (x >> 1);
  5632. x = x | (x >> 2);
  5633. x = x | (x >> 4);
  5634. x = x | (x >> 8);
  5635. x = x | (x >> 16);
  5636. return x - (x >> 1);
  5637. };
  5638. /**
  5639. * Find the nearest power of two.
  5640. * @param x Number to start search from.
  5641. * @return Next nearest power of two.
  5642. */
  5643. Tools.NearestPOT = function (x) {
  5644. var c = Tools.CeilingPOT(x);
  5645. var f = Tools.FloorPOT(x);
  5646. return (c - x) > (x - f) ? f : c;
  5647. };
  5648. Tools.GetExponentOfTwo = function (value, max, mode) {
  5649. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5650. var pot;
  5651. switch (mode) {
  5652. case BABYLON.Engine.SCALEMODE_FLOOR:
  5653. pot = Tools.FloorPOT(value);
  5654. break;
  5655. case BABYLON.Engine.SCALEMODE_NEAREST:
  5656. pot = Tools.NearestPOT(value);
  5657. break;
  5658. case BABYLON.Engine.SCALEMODE_CEILING:
  5659. pot = Tools.CeilingPOT(value);
  5660. break;
  5661. }
  5662. return Math.min(pot, max);
  5663. };
  5664. Tools.GetFilename = function (path) {
  5665. var index = path.lastIndexOf("/");
  5666. if (index < 0)
  5667. return path;
  5668. return path.substring(index + 1);
  5669. };
  5670. Tools.GetDOMTextContent = function (element) {
  5671. var result = "";
  5672. var child = element.firstChild;
  5673. while (child) {
  5674. if (child.nodeType === 3) {
  5675. result += child.textContent;
  5676. }
  5677. child = child.nextSibling;
  5678. }
  5679. return result;
  5680. };
  5681. Tools.ToDegrees = function (angle) {
  5682. return angle * 180 / Math.PI;
  5683. };
  5684. Tools.ToRadians = function (angle) {
  5685. return angle * Math.PI / 180;
  5686. };
  5687. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5688. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5689. var output = "";
  5690. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5691. var i = 0;
  5692. var bytes = new Uint8Array(buffer);
  5693. while (i < bytes.length) {
  5694. chr1 = bytes[i++];
  5695. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5696. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5697. enc1 = chr1 >> 2;
  5698. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5699. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5700. enc4 = chr3 & 63;
  5701. if (isNaN(chr2)) {
  5702. enc3 = enc4 = 64;
  5703. }
  5704. else if (isNaN(chr3)) {
  5705. enc4 = 64;
  5706. }
  5707. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5708. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5709. }
  5710. return "data:image/png;base64," + output;
  5711. };
  5712. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5713. if (bias === void 0) { bias = null; }
  5714. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5715. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5716. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5717. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5718. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5719. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5720. }
  5721. if (bias) {
  5722. minimum.x -= minimum.x * bias.x + bias.y;
  5723. minimum.y -= minimum.y * bias.x + bias.y;
  5724. minimum.z -= minimum.z * bias.x + bias.y;
  5725. maximum.x += maximum.x * bias.x + bias.y;
  5726. maximum.y += maximum.y * bias.x + bias.y;
  5727. maximum.z += maximum.z * bias.x + bias.y;
  5728. }
  5729. return {
  5730. minimum: minimum,
  5731. maximum: maximum
  5732. };
  5733. };
  5734. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5735. if (bias === void 0) { bias = null; }
  5736. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5737. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5738. if (!stride) {
  5739. stride = 3;
  5740. }
  5741. for (var index = start; index < start + count; index++) {
  5742. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5743. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5744. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5745. }
  5746. if (bias) {
  5747. minimum.x -= minimum.x * bias.x + bias.y;
  5748. minimum.y -= minimum.y * bias.x + bias.y;
  5749. minimum.z -= minimum.z * bias.x + bias.y;
  5750. maximum.x += maximum.x * bias.x + bias.y;
  5751. maximum.y += maximum.y * bias.x + bias.y;
  5752. maximum.z += maximum.z * bias.x + bias.y;
  5753. }
  5754. return {
  5755. minimum: minimum,
  5756. maximum: maximum
  5757. };
  5758. };
  5759. Tools.Vector2ArrayFeeder = function (array) {
  5760. return function (index) {
  5761. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5762. var length = isFloatArray ? array.length / 2 : array.length;
  5763. if (index >= length) {
  5764. return null;
  5765. }
  5766. if (isFloatArray) {
  5767. var fa = array;
  5768. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5769. }
  5770. var a = array;
  5771. return a[index];
  5772. };
  5773. };
  5774. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5775. if (bias === void 0) { bias = null; }
  5776. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5777. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5778. var i = 0;
  5779. var cur = feeder(i++);
  5780. while (cur) {
  5781. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5782. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5783. cur = feeder(i++);
  5784. }
  5785. if (bias) {
  5786. minimum.x -= minimum.x * bias.x + bias.y;
  5787. minimum.y -= minimum.y * bias.x + bias.y;
  5788. maximum.x += maximum.x * bias.x + bias.y;
  5789. maximum.y += maximum.y * bias.x + bias.y;
  5790. }
  5791. return {
  5792. minimum: minimum,
  5793. maximum: maximum
  5794. };
  5795. };
  5796. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5797. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5798. return undefined;
  5799. return Array.isArray(obj) ? obj : [obj];
  5800. };
  5801. // Misc.
  5802. Tools.GetPointerPrefix = function () {
  5803. var eventPrefix = "pointer";
  5804. // Check if pointer events are supported
  5805. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5806. eventPrefix = "mouse";
  5807. }
  5808. return eventPrefix;
  5809. };
  5810. /**
  5811. * @param func - the function to be called
  5812. * @param requester - the object that will request the next frame. Falls back to window.
  5813. */
  5814. Tools.QueueNewFrame = function (func, requester) {
  5815. if (requester === void 0) { requester = window; }
  5816. if (requester.requestAnimationFrame) {
  5817. return requester.requestAnimationFrame(func);
  5818. }
  5819. else if (requester.msRequestAnimationFrame) {
  5820. return requester.msRequestAnimationFrame(func);
  5821. }
  5822. else if (requester.webkitRequestAnimationFrame) {
  5823. return requester.webkitRequestAnimationFrame(func);
  5824. }
  5825. else if (requester.mozRequestAnimationFrame) {
  5826. return requester.mozRequestAnimationFrame(func);
  5827. }
  5828. else if (requester.oRequestAnimationFrame) {
  5829. return requester.oRequestAnimationFrame(func);
  5830. }
  5831. else {
  5832. return window.setTimeout(func, 16);
  5833. }
  5834. };
  5835. Tools.RequestFullscreen = function (element) {
  5836. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5837. if (!requestFunction)
  5838. return;
  5839. requestFunction.call(element);
  5840. };
  5841. Tools.ExitFullscreen = function () {
  5842. if (document.exitFullscreen) {
  5843. document.exitFullscreen();
  5844. }
  5845. else if (document.mozCancelFullScreen) {
  5846. document.mozCancelFullScreen();
  5847. }
  5848. else if (document.webkitCancelFullScreen) {
  5849. document.webkitCancelFullScreen();
  5850. }
  5851. else if (document.msCancelFullScreen) {
  5852. document.msCancelFullScreen();
  5853. }
  5854. };
  5855. Tools.SetCorsBehavior = function (url, img) {
  5856. if (Tools.CorsBehavior) {
  5857. switch (typeof (Tools.CorsBehavior)) {
  5858. case "function":
  5859. var result = Tools.CorsBehavior(url);
  5860. if (result) {
  5861. img.crossOrigin = result;
  5862. }
  5863. break;
  5864. case "string":
  5865. default:
  5866. img.crossOrigin = Tools.CorsBehavior;
  5867. break;
  5868. }
  5869. }
  5870. };
  5871. // External files
  5872. Tools.CleanUrl = function (url) {
  5873. url = url.replace(/#/mg, "%23");
  5874. return url;
  5875. };
  5876. Tools.LoadImage = function (url, onLoad, onError, database) {
  5877. if (url instanceof ArrayBuffer) {
  5878. url = Tools.EncodeArrayBufferTobase64(url);
  5879. }
  5880. url = Tools.CleanUrl(url);
  5881. url = Tools.PreprocessUrl(url);
  5882. var img = new Image();
  5883. if (url.substr(0, 5) !== "data:") {
  5884. Tools.SetCorsBehavior(url, img);
  5885. }
  5886. img.onload = function () {
  5887. onLoad(img);
  5888. };
  5889. img.onerror = function (err) {
  5890. Tools.Error("Error while trying to load image: " + url);
  5891. if (Tools.UseFallbackTexture) {
  5892. img.src = Tools.fallbackTexture;
  5893. onLoad(img);
  5894. }
  5895. else {
  5896. onError("Error while trying to load image: " + url, err);
  5897. }
  5898. };
  5899. var noIndexedDB = function () {
  5900. img.src = url;
  5901. };
  5902. var loadFromIndexedDB = function () {
  5903. database.loadImageFromDB(url, img);
  5904. };
  5905. //ANY database to do!
  5906. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5907. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5908. }
  5909. else {
  5910. if (url.indexOf("file:") !== 0) {
  5911. noIndexedDB();
  5912. }
  5913. else {
  5914. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5915. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5916. try {
  5917. var blobURL;
  5918. try {
  5919. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5920. }
  5921. catch (ex) {
  5922. // Chrome doesn't support oneTimeOnly parameter
  5923. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5924. }
  5925. img.src = blobURL;
  5926. }
  5927. catch (e) {
  5928. img.src = null;
  5929. }
  5930. }
  5931. else {
  5932. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5933. img.src = Tools.fallbackTexture;
  5934. }
  5935. }
  5936. }
  5937. return img;
  5938. };
  5939. //ANY
  5940. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5941. url = Tools.CleanUrl(url);
  5942. url = Tools.PreprocessUrl(url);
  5943. var noIndexedDB = function () {
  5944. var request = new XMLHttpRequest();
  5945. var loadUrl = Tools.BaseUrl + url;
  5946. request.open('GET', loadUrl, true);
  5947. if (useArrayBuffer) {
  5948. request.responseType = "arraybuffer";
  5949. }
  5950. request.onprogress = progressCallBack;
  5951. request.onreadystatechange = function () {
  5952. // In case of undefined state in some browsers.
  5953. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5954. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5955. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5956. callback(!useArrayBuffer ? request.responseText : request.response);
  5957. }
  5958. else {
  5959. var e = new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5960. if (onError) {
  5961. onError(request, e);
  5962. }
  5963. else {
  5964. throw e;
  5965. }
  5966. }
  5967. }
  5968. };
  5969. request.send(null);
  5970. };
  5971. var loadFromIndexedDB = function () {
  5972. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5973. };
  5974. if (url.indexOf("file:") !== -1) {
  5975. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5976. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5977. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5978. }
  5979. else {
  5980. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  5981. if (onError) {
  5982. var e = new Error(errorMessage);
  5983. onError(undefined, e);
  5984. }
  5985. else {
  5986. Tools.Error(errorMessage);
  5987. }
  5988. }
  5989. }
  5990. else {
  5991. // Caching all files
  5992. if (database && database.enableSceneOffline) {
  5993. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5994. }
  5995. else {
  5996. noIndexedDB();
  5997. }
  5998. }
  5999. };
  6000. /**
  6001. * Load a script (identified by an url). When the url returns, the
  6002. * content of this file is added into a new script element, attached to the DOM (body element)
  6003. */
  6004. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6005. var head = document.getElementsByTagName('head')[0];
  6006. var script = document.createElement('script');
  6007. script.type = 'text/javascript';
  6008. script.src = scriptUrl;
  6009. var self = this;
  6010. script.onload = function () {
  6011. if (onSuccess) {
  6012. onSuccess();
  6013. }
  6014. };
  6015. script.onerror = function (e) {
  6016. if (onError) {
  6017. onError("Unable to load script", e);
  6018. }
  6019. };
  6020. head.appendChild(script);
  6021. };
  6022. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6023. var reader = new FileReader();
  6024. reader.onload = function (e) {
  6025. //target doesn't have result from ts 1.3
  6026. callback(e.target['result']);
  6027. };
  6028. reader.onprogress = progressCallback;
  6029. reader.readAsDataURL(fileToLoad);
  6030. };
  6031. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6032. var reader = new FileReader();
  6033. reader.onerror = function (e) {
  6034. Tools.Log("Error while reading file: " + fileToLoad.name);
  6035. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6036. };
  6037. reader.onload = function (e) {
  6038. //target doesn't have result from ts 1.3
  6039. callback(e.target['result']);
  6040. };
  6041. reader.onprogress = progressCallBack;
  6042. if (!useArrayBuffer) {
  6043. // Asynchronous read
  6044. reader.readAsText(fileToLoad);
  6045. }
  6046. else {
  6047. reader.readAsArrayBuffer(fileToLoad);
  6048. }
  6049. };
  6050. //returns a downloadable url to a file content.
  6051. Tools.FileAsURL = function (content) {
  6052. var fileBlob = new Blob([content]);
  6053. var url = window.URL || window.webkitURL;
  6054. var link = url.createObjectURL(fileBlob);
  6055. return link;
  6056. };
  6057. // Misc.
  6058. Tools.Format = function (value, decimals) {
  6059. if (decimals === void 0) { decimals = 2; }
  6060. return value.toFixed(decimals);
  6061. };
  6062. Tools.CheckExtends = function (v, min, max) {
  6063. if (v.x < min.x)
  6064. min.x = v.x;
  6065. if (v.y < min.y)
  6066. min.y = v.y;
  6067. if (v.z < min.z)
  6068. min.z = v.z;
  6069. if (v.x > max.x)
  6070. max.x = v.x;
  6071. if (v.y > max.y)
  6072. max.y = v.y;
  6073. if (v.z > max.z)
  6074. max.z = v.z;
  6075. };
  6076. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6077. for (var prop in source) {
  6078. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6079. continue;
  6080. }
  6081. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6082. continue;
  6083. }
  6084. var sourceValue = source[prop];
  6085. var typeOfSourceValue = typeof sourceValue;
  6086. if (typeOfSourceValue === "function") {
  6087. continue;
  6088. }
  6089. if (typeOfSourceValue === "object") {
  6090. if (sourceValue instanceof Array) {
  6091. destination[prop] = [];
  6092. if (sourceValue.length > 0) {
  6093. if (typeof sourceValue[0] == "object") {
  6094. for (var index = 0; index < sourceValue.length; index++) {
  6095. var clonedValue = cloneValue(sourceValue[index], destination);
  6096. if (destination[prop].indexOf(clonedValue) === -1) {
  6097. destination[prop].push(clonedValue);
  6098. }
  6099. }
  6100. }
  6101. else {
  6102. destination[prop] = sourceValue.slice(0);
  6103. }
  6104. }
  6105. }
  6106. else {
  6107. destination[prop] = cloneValue(sourceValue, destination);
  6108. }
  6109. }
  6110. else {
  6111. destination[prop] = sourceValue;
  6112. }
  6113. }
  6114. };
  6115. Tools.IsEmpty = function (obj) {
  6116. for (var i in obj) {
  6117. return false;
  6118. }
  6119. return true;
  6120. };
  6121. Tools.RegisterTopRootEvents = function (events) {
  6122. for (var index = 0; index < events.length; index++) {
  6123. var event = events[index];
  6124. window.addEventListener(event.name, event.handler, false);
  6125. try {
  6126. if (window.parent) {
  6127. window.parent.addEventListener(event.name, event.handler, false);
  6128. }
  6129. }
  6130. catch (e) {
  6131. // Silently fails...
  6132. }
  6133. }
  6134. };
  6135. Tools.UnregisterTopRootEvents = function (events) {
  6136. for (var index = 0; index < events.length; index++) {
  6137. var event = events[index];
  6138. window.removeEventListener(event.name, event.handler);
  6139. try {
  6140. if (window.parent) {
  6141. window.parent.removeEventListener(event.name, event.handler);
  6142. }
  6143. }
  6144. catch (e) {
  6145. // Silently fails...
  6146. }
  6147. }
  6148. };
  6149. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6150. if (mimeType === void 0) { mimeType = "image/png"; }
  6151. // Read the contents of the framebuffer
  6152. var numberOfChannelsByLine = width * 4;
  6153. var halfHeight = height / 2;
  6154. //Reading datas from WebGL
  6155. var data = engine.readPixels(0, 0, width, height);
  6156. //To flip image on Y axis.
  6157. for (var i = 0; i < halfHeight; i++) {
  6158. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6159. var currentCell = j + i * numberOfChannelsByLine;
  6160. var targetLine = height - i - 1;
  6161. var targetCell = j + targetLine * numberOfChannelsByLine;
  6162. var temp = data[currentCell];
  6163. data[currentCell] = data[targetCell];
  6164. data[targetCell] = temp;
  6165. }
  6166. }
  6167. // Create a 2D canvas to store the result
  6168. if (!screenshotCanvas) {
  6169. screenshotCanvas = document.createElement('canvas');
  6170. }
  6171. screenshotCanvas.width = width;
  6172. screenshotCanvas.height = height;
  6173. var context = screenshotCanvas.getContext('2d');
  6174. // Copy the pixels to a 2D canvas
  6175. var imageData = context.createImageData(width, height);
  6176. var castData = (imageData.data);
  6177. castData.set(data);
  6178. context.putImageData(imageData, 0, 0);
  6179. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6180. };
  6181. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6182. if (mimeType === void 0) { mimeType = "image/png"; }
  6183. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6184. if (successCallback) {
  6185. successCallback(base64Image);
  6186. }
  6187. else {
  6188. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6189. if (("download" in document.createElement("a"))) {
  6190. var a = window.document.createElement("a");
  6191. a.href = base64Image;
  6192. var date = new Date();
  6193. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6194. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6195. window.document.body.appendChild(a);
  6196. a.addEventListener("click", function () {
  6197. a.parentElement.removeChild(a);
  6198. });
  6199. a.click();
  6200. //Or opening a new tab with the image if it is not possible to automatically start download.
  6201. }
  6202. else {
  6203. var newWindow = window.open("");
  6204. var img = newWindow.document.createElement("img");
  6205. img.src = base64Image;
  6206. newWindow.document.body.appendChild(img);
  6207. }
  6208. }
  6209. };
  6210. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6211. if (mimeType === void 0) { mimeType = "image/png"; }
  6212. var width;
  6213. var height;
  6214. // If a precision value is specified
  6215. if (size.precision) {
  6216. width = Math.round(engine.getRenderWidth() * size.precision);
  6217. height = Math.round(width / engine.getAspectRatio(camera));
  6218. }
  6219. else if (size.width && size.height) {
  6220. width = size.width;
  6221. height = size.height;
  6222. }
  6223. else if (size.width && !size.height) {
  6224. width = size.width;
  6225. height = Math.round(width / engine.getAspectRatio(camera));
  6226. }
  6227. else if (size.height && !size.width) {
  6228. height = size.height;
  6229. width = Math.round(height * engine.getAspectRatio(camera));
  6230. }
  6231. else if (!isNaN(size)) {
  6232. height = size;
  6233. width = size;
  6234. }
  6235. else {
  6236. Tools.Error("Invalid 'size' parameter !");
  6237. return;
  6238. }
  6239. if (!screenshotCanvas) {
  6240. screenshotCanvas = document.createElement('canvas');
  6241. }
  6242. screenshotCanvas.width = width;
  6243. screenshotCanvas.height = height;
  6244. var renderContext = screenshotCanvas.getContext("2d");
  6245. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6246. var newWidth = width;
  6247. var newHeight = newWidth / ratio;
  6248. if (newHeight > height) {
  6249. newHeight = height;
  6250. newWidth = newHeight * ratio;
  6251. }
  6252. var offsetX = Math.max(0, width - newWidth) / 2;
  6253. var offsetY = Math.max(0, height - newHeight) / 2;
  6254. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6255. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6256. };
  6257. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6258. if (mimeType === void 0) { mimeType = "image/png"; }
  6259. if (samples === void 0) { samples = 1; }
  6260. var width;
  6261. var height;
  6262. //If a precision value is specified
  6263. if (size.precision) {
  6264. width = Math.round(engine.getRenderWidth() * size.precision);
  6265. height = Math.round(width / engine.getAspectRatio(camera));
  6266. size = { width: width, height: height };
  6267. }
  6268. else if (size.width && size.height) {
  6269. width = size.width;
  6270. height = size.height;
  6271. }
  6272. else if (size.width && !size.height) {
  6273. width = size.width;
  6274. height = Math.round(width / engine.getAspectRatio(camera));
  6275. size = { width: width, height: height };
  6276. }
  6277. else if (size.height && !size.width) {
  6278. height = size.height;
  6279. width = Math.round(height * engine.getAspectRatio(camera));
  6280. size = { width: width, height: height };
  6281. }
  6282. else if (!isNaN(size)) {
  6283. height = size;
  6284. width = size;
  6285. }
  6286. else {
  6287. Tools.Error("Invalid 'size' parameter !");
  6288. return;
  6289. }
  6290. var scene = camera.getScene();
  6291. var previousCamera = null;
  6292. if (scene.activeCamera !== camera) {
  6293. previousCamera = scene.activeCamera;
  6294. scene.activeCamera = camera;
  6295. }
  6296. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6297. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6298. texture.renderList = null;
  6299. texture.samples = samples;
  6300. texture.onAfterRenderObservable.add(function () {
  6301. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6302. });
  6303. scene.incrementRenderId();
  6304. scene.resetCachedMaterial();
  6305. texture.render(true);
  6306. texture.dispose();
  6307. if (previousCamera) {
  6308. scene.activeCamera = previousCamera;
  6309. }
  6310. camera.getProjectionMatrix(true); // Force cache refresh;
  6311. };
  6312. // XHR response validator for local file scenario
  6313. Tools.ValidateXHRData = function (xhr, dataType) {
  6314. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6315. if (dataType === void 0) { dataType = 7; }
  6316. try {
  6317. if (dataType & 1) {
  6318. if (xhr.responseText && xhr.responseText.length > 0) {
  6319. return true;
  6320. }
  6321. else if (dataType === 1) {
  6322. return false;
  6323. }
  6324. }
  6325. if (dataType & 2) {
  6326. // Check header width and height since there is no "TGA" magic number
  6327. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6328. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6329. return true;
  6330. }
  6331. else if (dataType === 2) {
  6332. return false;
  6333. }
  6334. }
  6335. if (dataType & 4) {
  6336. // Check for the "DDS" magic number
  6337. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6338. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6339. return true;
  6340. }
  6341. else {
  6342. return false;
  6343. }
  6344. }
  6345. }
  6346. catch (e) {
  6347. // Global protection
  6348. }
  6349. return false;
  6350. };
  6351. /**
  6352. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6353. * Be aware Math.random() could cause collisions, but:
  6354. * "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"
  6355. */
  6356. Tools.RandomId = function () {
  6357. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6358. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6359. return v.toString(16);
  6360. });
  6361. };
  6362. Object.defineProperty(Tools, "NoneLogLevel", {
  6363. get: function () {
  6364. return Tools._NoneLogLevel;
  6365. },
  6366. enumerable: true,
  6367. configurable: true
  6368. });
  6369. Object.defineProperty(Tools, "MessageLogLevel", {
  6370. get: function () {
  6371. return Tools._MessageLogLevel;
  6372. },
  6373. enumerable: true,
  6374. configurable: true
  6375. });
  6376. Object.defineProperty(Tools, "WarningLogLevel", {
  6377. get: function () {
  6378. return Tools._WarningLogLevel;
  6379. },
  6380. enumerable: true,
  6381. configurable: true
  6382. });
  6383. Object.defineProperty(Tools, "ErrorLogLevel", {
  6384. get: function () {
  6385. return Tools._ErrorLogLevel;
  6386. },
  6387. enumerable: true,
  6388. configurable: true
  6389. });
  6390. Object.defineProperty(Tools, "AllLogLevel", {
  6391. get: function () {
  6392. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6393. },
  6394. enumerable: true,
  6395. configurable: true
  6396. });
  6397. Tools._AddLogEntry = function (entry) {
  6398. Tools._LogCache = entry + Tools._LogCache;
  6399. if (Tools.OnNewCacheEntry) {
  6400. Tools.OnNewCacheEntry(entry);
  6401. }
  6402. };
  6403. Tools._FormatMessage = function (message) {
  6404. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6405. var date = new Date();
  6406. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6407. };
  6408. Tools._LogDisabled = function (message) {
  6409. // nothing to do
  6410. };
  6411. Tools._LogEnabled = function (message) {
  6412. var formattedMessage = Tools._FormatMessage(message);
  6413. console.log("BJS - " + formattedMessage);
  6414. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6415. Tools._AddLogEntry(entry);
  6416. };
  6417. Tools._WarnDisabled = function (message) {
  6418. // nothing to do
  6419. };
  6420. Tools._WarnEnabled = function (message) {
  6421. var formattedMessage = Tools._FormatMessage(message);
  6422. console.warn("BJS - " + formattedMessage);
  6423. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6424. Tools._AddLogEntry(entry);
  6425. };
  6426. Tools._ErrorDisabled = function (message) {
  6427. // nothing to do
  6428. };
  6429. Tools._ErrorEnabled = function (message) {
  6430. Tools.errorsCount++;
  6431. var formattedMessage = Tools._FormatMessage(message);
  6432. console.error("BJS - " + formattedMessage);
  6433. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6434. Tools._AddLogEntry(entry);
  6435. };
  6436. Object.defineProperty(Tools, "LogCache", {
  6437. get: function () {
  6438. return Tools._LogCache;
  6439. },
  6440. enumerable: true,
  6441. configurable: true
  6442. });
  6443. Tools.ClearLogCache = function () {
  6444. Tools._LogCache = "";
  6445. Tools.errorsCount = 0;
  6446. };
  6447. Object.defineProperty(Tools, "LogLevels", {
  6448. set: function (level) {
  6449. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6450. Tools.Log = Tools._LogEnabled;
  6451. }
  6452. else {
  6453. Tools.Log = Tools._LogDisabled;
  6454. }
  6455. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6456. Tools.Warn = Tools._WarnEnabled;
  6457. }
  6458. else {
  6459. Tools.Warn = Tools._WarnDisabled;
  6460. }
  6461. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6462. Tools.Error = Tools._ErrorEnabled;
  6463. }
  6464. else {
  6465. Tools.Error = Tools._ErrorDisabled;
  6466. }
  6467. },
  6468. enumerable: true,
  6469. configurable: true
  6470. });
  6471. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6472. get: function () {
  6473. return Tools._PerformanceNoneLogLevel;
  6474. },
  6475. enumerable: true,
  6476. configurable: true
  6477. });
  6478. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6479. get: function () {
  6480. return Tools._PerformanceUserMarkLogLevel;
  6481. },
  6482. enumerable: true,
  6483. configurable: true
  6484. });
  6485. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6486. get: function () {
  6487. return Tools._PerformanceConsoleLogLevel;
  6488. },
  6489. enumerable: true,
  6490. configurable: true
  6491. });
  6492. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6493. set: function (level) {
  6494. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6495. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6496. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6497. return;
  6498. }
  6499. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6500. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6501. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6502. return;
  6503. }
  6504. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6505. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6506. },
  6507. enumerable: true,
  6508. configurable: true
  6509. });
  6510. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6511. };
  6512. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6513. };
  6514. Tools._StartUserMark = function (counterName, condition) {
  6515. if (condition === void 0) { condition = true; }
  6516. if (!condition || !Tools._performance.mark) {
  6517. return;
  6518. }
  6519. Tools._performance.mark(counterName + "-Begin");
  6520. };
  6521. Tools._EndUserMark = function (counterName, condition) {
  6522. if (condition === void 0) { condition = true; }
  6523. if (!condition || !Tools._performance.mark) {
  6524. return;
  6525. }
  6526. Tools._performance.mark(counterName + "-End");
  6527. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6528. };
  6529. Tools._StartPerformanceConsole = function (counterName, condition) {
  6530. if (condition === void 0) { condition = true; }
  6531. if (!condition) {
  6532. return;
  6533. }
  6534. Tools._StartUserMark(counterName, condition);
  6535. if (console.time) {
  6536. console.time(counterName);
  6537. }
  6538. };
  6539. Tools._EndPerformanceConsole = function (counterName, condition) {
  6540. if (condition === void 0) { condition = true; }
  6541. if (!condition) {
  6542. return;
  6543. }
  6544. Tools._EndUserMark(counterName, condition);
  6545. if (console.time) {
  6546. console.timeEnd(counterName);
  6547. }
  6548. };
  6549. Object.defineProperty(Tools, "Now", {
  6550. get: function () {
  6551. if (window.performance && window.performance.now) {
  6552. return window.performance.now();
  6553. }
  6554. return new Date().getTime();
  6555. },
  6556. enumerable: true,
  6557. configurable: true
  6558. });
  6559. /**
  6560. * This method will return the name of the class used to create the instance of the given object.
  6561. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6562. * @param object the object to get the class name from
  6563. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6564. */
  6565. Tools.GetClassName = function (object, isType) {
  6566. if (isType === void 0) { isType = false; }
  6567. var name = null;
  6568. if (!isType && object.getClassName) {
  6569. name = object.getClassName();
  6570. }
  6571. else {
  6572. if (object instanceof Object) {
  6573. var classObj = isType ? object : Object.getPrototypeOf(object);
  6574. name = classObj.constructor["__bjsclassName__"];
  6575. }
  6576. if (!name) {
  6577. name = typeof object;
  6578. }
  6579. }
  6580. return name;
  6581. };
  6582. Tools.first = function (array, predicate) {
  6583. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6584. var el = array_1[_i];
  6585. if (predicate(el)) {
  6586. return el;
  6587. }
  6588. }
  6589. };
  6590. /**
  6591. * This method will return the name of the full name of the class, including its owning module (if any).
  6592. * 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).
  6593. * @param object the object to get the class name from
  6594. * @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.
  6595. */
  6596. Tools.getFullClassName = function (object, isType) {
  6597. if (isType === void 0) { isType = false; }
  6598. var className = null;
  6599. var moduleName = null;
  6600. if (!isType && object.getClassName) {
  6601. className = object.getClassName();
  6602. }
  6603. else {
  6604. if (object instanceof Object) {
  6605. var classObj = isType ? object : Object.getPrototypeOf(object);
  6606. className = classObj.constructor["__bjsclassName__"];
  6607. moduleName = classObj.constructor["__bjsmoduleName__"];
  6608. }
  6609. if (!className) {
  6610. className = typeof object;
  6611. }
  6612. }
  6613. if (!className) {
  6614. return null;
  6615. }
  6616. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6617. };
  6618. /**
  6619. * 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.
  6620. * @param array
  6621. */
  6622. Tools.arrayOrStringFeeder = function (array) {
  6623. return function (index) {
  6624. if (index >= array.length) {
  6625. return null;
  6626. }
  6627. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6628. if (val && val.getHashCode) {
  6629. val = val.getHashCode();
  6630. }
  6631. if (typeof val === "string") {
  6632. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6633. }
  6634. return val;
  6635. };
  6636. };
  6637. /**
  6638. * Compute the hashCode of a stream of number
  6639. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6640. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6641. * @return the hash code computed
  6642. */
  6643. Tools.hashCodeFromStream = function (feeder) {
  6644. // Based from here: http://stackoverflow.com/a/7616484/802124
  6645. var hash = 0;
  6646. var index = 0;
  6647. var chr = feeder(index++);
  6648. while (chr != null) {
  6649. hash = ((hash << 5) - hash) + chr;
  6650. hash |= 0; // Convert to 32bit integer
  6651. chr = feeder(index++);
  6652. }
  6653. return hash;
  6654. };
  6655. return Tools;
  6656. }());
  6657. Tools.BaseUrl = "";
  6658. Tools.CorsBehavior = "anonymous";
  6659. Tools.UseFallbackTexture = true;
  6660. /**
  6661. * Use this object to register external classes like custom textures or material
  6662. * to allow the laoders to instantiate them
  6663. */
  6664. Tools.RegisteredExternalClasses = {};
  6665. // Used in case of a texture loading problem
  6666. 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";
  6667. Tools.PreprocessUrl = function (url) {
  6668. return url;
  6669. };
  6670. // Logs
  6671. Tools._NoneLogLevel = 0;
  6672. Tools._MessageLogLevel = 1;
  6673. Tools._WarningLogLevel = 2;
  6674. Tools._ErrorLogLevel = 4;
  6675. Tools._LogCache = "";
  6676. Tools.errorsCount = 0;
  6677. Tools.Log = Tools._LogEnabled;
  6678. Tools.Warn = Tools._WarnEnabled;
  6679. Tools.Error = Tools._ErrorEnabled;
  6680. // Performances
  6681. Tools._PerformanceNoneLogLevel = 0;
  6682. Tools._PerformanceUserMarkLogLevel = 1;
  6683. Tools._PerformanceConsoleLogLevel = 2;
  6684. Tools._performance = window.performance;
  6685. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6686. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6687. BABYLON.Tools = Tools;
  6688. /**
  6689. * This class is used to track a performance counter which is number based.
  6690. * The user has access to many properties which give statistics of different nature
  6691. *
  6692. * The implementer can track two kinds of Performance Counter: time and count
  6693. * 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.
  6694. * 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.
  6695. */
  6696. var PerfCounter = (function () {
  6697. function PerfCounter() {
  6698. this._startMonitoringTime = 0;
  6699. this._min = 0;
  6700. this._max = 0;
  6701. this._average = 0;
  6702. this._lastSecAverage = 0;
  6703. this._current = 0;
  6704. this._totalValueCount = 0;
  6705. this._totalAccumulated = 0;
  6706. this._lastSecAccumulated = 0;
  6707. this._lastSecTime = 0;
  6708. this._lastSecValueCount = 0;
  6709. }
  6710. Object.defineProperty(PerfCounter.prototype, "min", {
  6711. /**
  6712. * Returns the smallest value ever
  6713. */
  6714. get: function () {
  6715. return this._min;
  6716. },
  6717. enumerable: true,
  6718. configurable: true
  6719. });
  6720. Object.defineProperty(PerfCounter.prototype, "max", {
  6721. /**
  6722. * Returns the biggest value ever
  6723. */
  6724. get: function () {
  6725. return this._max;
  6726. },
  6727. enumerable: true,
  6728. configurable: true
  6729. });
  6730. Object.defineProperty(PerfCounter.prototype, "average", {
  6731. /**
  6732. * Returns the average value since the performance counter is running
  6733. */
  6734. get: function () {
  6735. return this._average;
  6736. },
  6737. enumerable: true,
  6738. configurable: true
  6739. });
  6740. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6741. /**
  6742. * Returns the average value of the last second the counter was monitored
  6743. */
  6744. get: function () {
  6745. return this._lastSecAverage;
  6746. },
  6747. enumerable: true,
  6748. configurable: true
  6749. });
  6750. Object.defineProperty(PerfCounter.prototype, "current", {
  6751. /**
  6752. * Returns the current value
  6753. */
  6754. get: function () {
  6755. return this._current;
  6756. },
  6757. enumerable: true,
  6758. configurable: true
  6759. });
  6760. Object.defineProperty(PerfCounter.prototype, "total", {
  6761. get: function () {
  6762. return this._totalAccumulated;
  6763. },
  6764. enumerable: true,
  6765. configurable: true
  6766. });
  6767. /**
  6768. * Call this method to start monitoring a new frame.
  6769. * 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.
  6770. */
  6771. PerfCounter.prototype.fetchNewFrame = function () {
  6772. this._totalValueCount++;
  6773. this._current = 0;
  6774. this._lastSecValueCount++;
  6775. };
  6776. /**
  6777. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6778. * @param newCount the count value to add to the monitored count
  6779. * @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.
  6780. */
  6781. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6782. if (!PerfCounter.Enabled) {
  6783. return;
  6784. }
  6785. this._current += newCount;
  6786. if (fetchResult) {
  6787. this._fetchResult();
  6788. }
  6789. };
  6790. /**
  6791. * Start monitoring this performance counter
  6792. */
  6793. PerfCounter.prototype.beginMonitoring = function () {
  6794. if (!PerfCounter.Enabled) {
  6795. return;
  6796. }
  6797. this._startMonitoringTime = Tools.Now;
  6798. };
  6799. /**
  6800. * Compute the time lapsed since the previous beginMonitoring() call.
  6801. * @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
  6802. */
  6803. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6804. if (newFrame === void 0) { newFrame = true; }
  6805. if (!PerfCounter.Enabled) {
  6806. return;
  6807. }
  6808. if (newFrame) {
  6809. this.fetchNewFrame();
  6810. }
  6811. var currentTime = Tools.Now;
  6812. this._current = currentTime - this._startMonitoringTime;
  6813. if (newFrame) {
  6814. this._fetchResult();
  6815. }
  6816. };
  6817. PerfCounter.prototype._fetchResult = function () {
  6818. this._totalAccumulated += this._current;
  6819. this._lastSecAccumulated += this._current;
  6820. // Min/Max update
  6821. this._min = Math.min(this._min, this._current);
  6822. this._max = Math.max(this._max, this._current);
  6823. this._average = this._totalAccumulated / this._totalValueCount;
  6824. // Reset last sec?
  6825. var now = Tools.Now;
  6826. if ((now - this._lastSecTime) > 1000) {
  6827. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6828. this._lastSecTime = now;
  6829. this._lastSecAccumulated = 0;
  6830. this._lastSecValueCount = 0;
  6831. }
  6832. };
  6833. return PerfCounter;
  6834. }());
  6835. PerfCounter.Enabled = true;
  6836. BABYLON.PerfCounter = PerfCounter;
  6837. /**
  6838. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6839. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6840. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6841. * @param name The name of the class, case should be preserved
  6842. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6843. */
  6844. function className(name, module) {
  6845. return function (target) {
  6846. target["__bjsclassName__"] = name;
  6847. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6848. };
  6849. }
  6850. BABYLON.className = className;
  6851. /**
  6852. * An implementation of a loop for asynchronous functions.
  6853. */
  6854. var AsyncLoop = (function () {
  6855. /**
  6856. * Constroctor.
  6857. * @param iterations the number of iterations.
  6858. * @param _fn the function to run each iteration
  6859. * @param _successCallback the callback that will be called upon succesful execution
  6860. * @param offset starting offset.
  6861. */
  6862. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6863. if (offset === void 0) { offset = 0; }
  6864. this.iterations = iterations;
  6865. this._fn = _fn;
  6866. this._successCallback = _successCallback;
  6867. this.index = offset - 1;
  6868. this._done = false;
  6869. }
  6870. /**
  6871. * Execute the next iteration. Must be called after the last iteration was finished.
  6872. */
  6873. AsyncLoop.prototype.executeNext = function () {
  6874. if (!this._done) {
  6875. if (this.index + 1 < this.iterations) {
  6876. ++this.index;
  6877. this._fn(this);
  6878. }
  6879. else {
  6880. this.breakLoop();
  6881. }
  6882. }
  6883. };
  6884. /**
  6885. * Break the loop and run the success callback.
  6886. */
  6887. AsyncLoop.prototype.breakLoop = function () {
  6888. this._done = true;
  6889. this._successCallback();
  6890. };
  6891. /**
  6892. * Helper function
  6893. */
  6894. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6895. if (offset === void 0) { offset = 0; }
  6896. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6897. loop.executeNext();
  6898. return loop;
  6899. };
  6900. /**
  6901. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6902. * @param iterations total number of iterations
  6903. * @param syncedIterations number of synchronous iterations in each async iteration.
  6904. * @param fn the function to call each iteration.
  6905. * @param callback a success call back that will be called when iterating stops.
  6906. * @param breakFunction a break condition (optional)
  6907. * @param timeout timeout settings for the setTimeout function. default - 0.
  6908. * @constructor
  6909. */
  6910. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6911. if (timeout === void 0) { timeout = 0; }
  6912. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6913. if (breakFunction && breakFunction())
  6914. loop.breakLoop();
  6915. else {
  6916. setTimeout(function () {
  6917. for (var i = 0; i < syncedIterations; ++i) {
  6918. var iteration = (loop.index * syncedIterations) + i;
  6919. if (iteration >= iterations)
  6920. break;
  6921. fn(iteration);
  6922. if (breakFunction && breakFunction()) {
  6923. loop.breakLoop();
  6924. break;
  6925. }
  6926. }
  6927. loop.executeNext();
  6928. }, timeout);
  6929. }
  6930. }, callback);
  6931. };
  6932. return AsyncLoop;
  6933. }());
  6934. BABYLON.AsyncLoop = AsyncLoop;
  6935. })(BABYLON || (BABYLON = {}));
  6936. //# sourceMappingURL=babylon.tools.js.map
  6937. var BABYLON;
  6938. (function (BABYLON) {
  6939. var Internals;
  6940. (function (Internals) {
  6941. var _AlphaState = (function () {
  6942. /**
  6943. * Initializes the state.
  6944. */
  6945. function _AlphaState() {
  6946. this._isAlphaBlendDirty = false;
  6947. this._isBlendFunctionParametersDirty = false;
  6948. this._isBlendEquationParametersDirty = false;
  6949. this._isBlendConstantsDirty = false;
  6950. this._alphaBlend = false;
  6951. this._blendFunctionParameters = new Array(4);
  6952. this._blendEquationParameters = new Array(2);
  6953. this._blendConstants = new Array(4);
  6954. this.reset();
  6955. }
  6956. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6957. get: function () {
  6958. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6959. },
  6960. enumerable: true,
  6961. configurable: true
  6962. });
  6963. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6964. get: function () {
  6965. return this._alphaBlend;
  6966. },
  6967. set: function (value) {
  6968. if (this._alphaBlend === value) {
  6969. return;
  6970. }
  6971. this._alphaBlend = value;
  6972. this._isAlphaBlendDirty = true;
  6973. },
  6974. enumerable: true,
  6975. configurable: true
  6976. });
  6977. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6978. if (this._blendConstants[0] === r &&
  6979. this._blendConstants[1] === g &&
  6980. this._blendConstants[2] === b &&
  6981. this._blendConstants[3] === a) {
  6982. return;
  6983. }
  6984. this._blendConstants[0] = r;
  6985. this._blendConstants[1] = g;
  6986. this._blendConstants[2] = b;
  6987. this._blendConstants[3] = a;
  6988. this._isBlendConstantsDirty = true;
  6989. };
  6990. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6991. if (this._blendFunctionParameters[0] === value0 &&
  6992. this._blendFunctionParameters[1] === value1 &&
  6993. this._blendFunctionParameters[2] === value2 &&
  6994. this._blendFunctionParameters[3] === value3) {
  6995. return;
  6996. }
  6997. this._blendFunctionParameters[0] = value0;
  6998. this._blendFunctionParameters[1] = value1;
  6999. this._blendFunctionParameters[2] = value2;
  7000. this._blendFunctionParameters[3] = value3;
  7001. this._isBlendFunctionParametersDirty = true;
  7002. };
  7003. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7004. if (this._blendEquationParameters[0] === rgb &&
  7005. this._blendEquationParameters[1] === alpha) {
  7006. return;
  7007. }
  7008. this._blendEquationParameters[0] = rgb;
  7009. this._blendEquationParameters[1] = alpha;
  7010. this._isBlendEquationParametersDirty = true;
  7011. };
  7012. _AlphaState.prototype.reset = function () {
  7013. this._alphaBlend = false;
  7014. this._blendFunctionParameters[0] = null;
  7015. this._blendFunctionParameters[1] = null;
  7016. this._blendFunctionParameters[2] = null;
  7017. this._blendFunctionParameters[3] = null;
  7018. this._blendEquationParameters[0] = null;
  7019. this._blendEquationParameters[1] = null;
  7020. this._blendConstants[0] = null;
  7021. this._blendConstants[1] = null;
  7022. this._blendConstants[2] = null;
  7023. this._blendConstants[3] = null;
  7024. this._isAlphaBlendDirty = true;
  7025. this._isBlendFunctionParametersDirty = false;
  7026. this._isBlendEquationParametersDirty = false;
  7027. this._isBlendConstantsDirty = false;
  7028. };
  7029. _AlphaState.prototype.apply = function (gl) {
  7030. if (!this.isDirty) {
  7031. return;
  7032. }
  7033. // Alpha blend
  7034. if (this._isAlphaBlendDirty) {
  7035. if (this._alphaBlend) {
  7036. gl.enable(gl.BLEND);
  7037. }
  7038. else {
  7039. gl.disable(gl.BLEND);
  7040. }
  7041. this._isAlphaBlendDirty = false;
  7042. }
  7043. // Alpha function
  7044. if (this._isBlendFunctionParametersDirty) {
  7045. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7046. this._isBlendFunctionParametersDirty = false;
  7047. }
  7048. // Alpha equation
  7049. if (this._isBlendEquationParametersDirty) {
  7050. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7051. this._isBlendEquationParametersDirty = false;
  7052. }
  7053. // Constants
  7054. if (this._isBlendConstantsDirty) {
  7055. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7056. this._isBlendConstantsDirty = false;
  7057. }
  7058. };
  7059. return _AlphaState;
  7060. }());
  7061. Internals._AlphaState = _AlphaState;
  7062. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7063. })(BABYLON || (BABYLON = {}));
  7064. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7065. var BABYLON;
  7066. (function (BABYLON) {
  7067. var Internals;
  7068. (function (Internals) {
  7069. var _DepthCullingState = (function () {
  7070. /**
  7071. * Initializes the state.
  7072. */
  7073. function _DepthCullingState() {
  7074. this._isDepthTestDirty = false;
  7075. this._isDepthMaskDirty = false;
  7076. this._isDepthFuncDirty = false;
  7077. this._isCullFaceDirty = false;
  7078. this._isCullDirty = false;
  7079. this._isZOffsetDirty = false;
  7080. this.reset();
  7081. }
  7082. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7083. get: function () {
  7084. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7085. },
  7086. enumerable: true,
  7087. configurable: true
  7088. });
  7089. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7090. get: function () {
  7091. return this._zOffset;
  7092. },
  7093. set: function (value) {
  7094. if (this._zOffset === value) {
  7095. return;
  7096. }
  7097. this._zOffset = value;
  7098. this._isZOffsetDirty = true;
  7099. },
  7100. enumerable: true,
  7101. configurable: true
  7102. });
  7103. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7104. get: function () {
  7105. return this._cullFace;
  7106. },
  7107. set: function (value) {
  7108. if (this._cullFace === value) {
  7109. return;
  7110. }
  7111. this._cullFace = value;
  7112. this._isCullFaceDirty = true;
  7113. },
  7114. enumerable: true,
  7115. configurable: true
  7116. });
  7117. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7118. get: function () {
  7119. return this._cull;
  7120. },
  7121. set: function (value) {
  7122. if (this._cull === value) {
  7123. return;
  7124. }
  7125. this._cull = value;
  7126. this._isCullDirty = true;
  7127. },
  7128. enumerable: true,
  7129. configurable: true
  7130. });
  7131. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7132. get: function () {
  7133. return this._depthFunc;
  7134. },
  7135. set: function (value) {
  7136. if (this._depthFunc === value) {
  7137. return;
  7138. }
  7139. this._depthFunc = value;
  7140. this._isDepthFuncDirty = true;
  7141. },
  7142. enumerable: true,
  7143. configurable: true
  7144. });
  7145. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7146. get: function () {
  7147. return this._depthMask;
  7148. },
  7149. set: function (value) {
  7150. if (this._depthMask === value) {
  7151. return;
  7152. }
  7153. this._depthMask = value;
  7154. this._isDepthMaskDirty = true;
  7155. },
  7156. enumerable: true,
  7157. configurable: true
  7158. });
  7159. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7160. get: function () {
  7161. return this._depthTest;
  7162. },
  7163. set: function (value) {
  7164. if (this._depthTest === value) {
  7165. return;
  7166. }
  7167. this._depthTest = value;
  7168. this._isDepthTestDirty = true;
  7169. },
  7170. enumerable: true,
  7171. configurable: true
  7172. });
  7173. _DepthCullingState.prototype.reset = function () {
  7174. this._depthMask = true;
  7175. this._depthTest = true;
  7176. this._depthFunc = null;
  7177. this._cullFace = null;
  7178. this._cull = null;
  7179. this._zOffset = 0;
  7180. this._isDepthTestDirty = true;
  7181. this._isDepthMaskDirty = true;
  7182. this._isDepthFuncDirty = false;
  7183. this._isCullFaceDirty = false;
  7184. this._isCullDirty = false;
  7185. this._isZOffsetDirty = false;
  7186. };
  7187. _DepthCullingState.prototype.apply = function (gl) {
  7188. if (!this.isDirty) {
  7189. return;
  7190. }
  7191. // Cull
  7192. if (this._isCullDirty) {
  7193. if (this.cull) {
  7194. gl.enable(gl.CULL_FACE);
  7195. }
  7196. else {
  7197. gl.disable(gl.CULL_FACE);
  7198. }
  7199. this._isCullDirty = false;
  7200. }
  7201. // Cull face
  7202. if (this._isCullFaceDirty) {
  7203. gl.cullFace(this.cullFace);
  7204. this._isCullFaceDirty = false;
  7205. }
  7206. // Depth mask
  7207. if (this._isDepthMaskDirty) {
  7208. gl.depthMask(this.depthMask);
  7209. this._isDepthMaskDirty = false;
  7210. }
  7211. // Depth test
  7212. if (this._isDepthTestDirty) {
  7213. if (this.depthTest) {
  7214. gl.enable(gl.DEPTH_TEST);
  7215. }
  7216. else {
  7217. gl.disable(gl.DEPTH_TEST);
  7218. }
  7219. this._isDepthTestDirty = false;
  7220. }
  7221. // Depth func
  7222. if (this._isDepthFuncDirty) {
  7223. gl.depthFunc(this.depthFunc);
  7224. this._isDepthFuncDirty = false;
  7225. }
  7226. // zOffset
  7227. if (this._isZOffsetDirty) {
  7228. if (this.zOffset) {
  7229. gl.enable(gl.POLYGON_OFFSET_FILL);
  7230. gl.polygonOffset(this.zOffset, 0);
  7231. }
  7232. else {
  7233. gl.disable(gl.POLYGON_OFFSET_FILL);
  7234. }
  7235. this._isZOffsetDirty = false;
  7236. }
  7237. };
  7238. return _DepthCullingState;
  7239. }());
  7240. Internals._DepthCullingState = _DepthCullingState;
  7241. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7242. })(BABYLON || (BABYLON = {}));
  7243. //# sourceMappingURL=babylon.depthCullingState.js.map
  7244. var BABYLON;
  7245. (function (BABYLON) {
  7246. var Internals;
  7247. (function (Internals) {
  7248. var _StencilState = (function () {
  7249. function _StencilState() {
  7250. this._isStencilTestDirty = false;
  7251. this._isStencilMaskDirty = false;
  7252. this._isStencilFuncDirty = false;
  7253. this._isStencilOpDirty = false;
  7254. this.reset();
  7255. }
  7256. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7257. get: function () {
  7258. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7259. },
  7260. enumerable: true,
  7261. configurable: true
  7262. });
  7263. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7264. get: function () {
  7265. return this._stencilFunc;
  7266. },
  7267. set: function (value) {
  7268. if (this._stencilFunc === value) {
  7269. return;
  7270. }
  7271. this._stencilFunc = value;
  7272. this._isStencilFuncDirty = true;
  7273. },
  7274. enumerable: true,
  7275. configurable: true
  7276. });
  7277. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7278. get: function () {
  7279. return this._stencilFuncRef;
  7280. },
  7281. set: function (value) {
  7282. if (this._stencilFuncRef === value) {
  7283. return;
  7284. }
  7285. this._stencilFuncRef = value;
  7286. this._isStencilFuncDirty = true;
  7287. },
  7288. enumerable: true,
  7289. configurable: true
  7290. });
  7291. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7292. get: function () {
  7293. return this._stencilFuncMask;
  7294. },
  7295. set: function (value) {
  7296. if (this._stencilFuncMask === value) {
  7297. return;
  7298. }
  7299. this._stencilFuncMask = value;
  7300. this._isStencilFuncDirty = true;
  7301. },
  7302. enumerable: true,
  7303. configurable: true
  7304. });
  7305. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7306. get: function () {
  7307. return this._stencilOpStencilFail;
  7308. },
  7309. set: function (value) {
  7310. if (this._stencilOpStencilFail === value) {
  7311. return;
  7312. }
  7313. this._stencilOpStencilFail = value;
  7314. this._isStencilOpDirty = true;
  7315. },
  7316. enumerable: true,
  7317. configurable: true
  7318. });
  7319. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7320. get: function () {
  7321. return this._stencilOpDepthFail;
  7322. },
  7323. set: function (value) {
  7324. if (this._stencilOpDepthFail === value) {
  7325. return;
  7326. }
  7327. this._stencilOpDepthFail = value;
  7328. this._isStencilOpDirty = true;
  7329. },
  7330. enumerable: true,
  7331. configurable: true
  7332. });
  7333. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7334. get: function () {
  7335. return this._stencilOpStencilDepthPass;
  7336. },
  7337. set: function (value) {
  7338. if (this._stencilOpStencilDepthPass === value) {
  7339. return;
  7340. }
  7341. this._stencilOpStencilDepthPass = value;
  7342. this._isStencilOpDirty = true;
  7343. },
  7344. enumerable: true,
  7345. configurable: true
  7346. });
  7347. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7348. get: function () {
  7349. return this._stencilMask;
  7350. },
  7351. set: function (value) {
  7352. if (this._stencilMask === value) {
  7353. return;
  7354. }
  7355. this._stencilMask = value;
  7356. this._isStencilMaskDirty = true;
  7357. },
  7358. enumerable: true,
  7359. configurable: true
  7360. });
  7361. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7362. get: function () {
  7363. return this._stencilTest;
  7364. },
  7365. set: function (value) {
  7366. if (this._stencilTest === value) {
  7367. return;
  7368. }
  7369. this._stencilTest = value;
  7370. this._isStencilTestDirty = true;
  7371. },
  7372. enumerable: true,
  7373. configurable: true
  7374. });
  7375. _StencilState.prototype.reset = function () {
  7376. this._stencilTest = false;
  7377. this._stencilMask = 0xFF;
  7378. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7379. this._stencilFuncRef = 1;
  7380. this._stencilFuncMask = 0xFF;
  7381. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7382. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7383. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7384. this._isStencilTestDirty = true;
  7385. this._isStencilMaskDirty = true;
  7386. this._isStencilFuncDirty = true;
  7387. this._isStencilOpDirty = true;
  7388. };
  7389. _StencilState.prototype.apply = function (gl) {
  7390. if (!this.isDirty) {
  7391. return;
  7392. }
  7393. // Stencil test
  7394. if (this._isStencilTestDirty) {
  7395. if (this.stencilTest) {
  7396. gl.enable(gl.STENCIL_TEST);
  7397. }
  7398. else {
  7399. gl.disable(gl.STENCIL_TEST);
  7400. }
  7401. this._isStencilTestDirty = false;
  7402. }
  7403. // Stencil mask
  7404. if (this._isStencilMaskDirty) {
  7405. gl.stencilMask(this.stencilMask);
  7406. this._isStencilMaskDirty = false;
  7407. }
  7408. // Stencil func
  7409. if (this._isStencilFuncDirty) {
  7410. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7411. this._isStencilFuncDirty = false;
  7412. }
  7413. // Stencil op
  7414. if (this._isStencilOpDirty) {
  7415. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7416. this._isStencilOpDirty = false;
  7417. }
  7418. };
  7419. return _StencilState;
  7420. }());
  7421. Internals._StencilState = _StencilState;
  7422. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7423. })(BABYLON || (BABYLON = {}));
  7424. //# sourceMappingURL=babylon.stencilState.js.map
  7425. var BABYLON;
  7426. (function (BABYLON) {
  7427. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7428. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7429. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7430. gl.compileShader(shader);
  7431. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7432. throw new Error(gl.getShaderInfoLog(shader));
  7433. }
  7434. return shader;
  7435. };
  7436. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7437. var magFilter = gl.NEAREST;
  7438. var minFilter = gl.NEAREST;
  7439. switch (samplingMode) {
  7440. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7441. magFilter = gl.LINEAR;
  7442. if (generateMipMaps) {
  7443. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7444. }
  7445. else {
  7446. minFilter = gl.LINEAR;
  7447. }
  7448. break;
  7449. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7450. magFilter = gl.LINEAR;
  7451. if (generateMipMaps) {
  7452. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7453. }
  7454. else {
  7455. minFilter = gl.LINEAR;
  7456. }
  7457. break;
  7458. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7459. magFilter = gl.NEAREST;
  7460. if (generateMipMaps) {
  7461. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7462. }
  7463. else {
  7464. minFilter = gl.NEAREST;
  7465. }
  7466. break;
  7467. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7468. magFilter = gl.NEAREST;
  7469. if (generateMipMaps) {
  7470. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7471. }
  7472. else {
  7473. minFilter = gl.NEAREST;
  7474. }
  7475. break;
  7476. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7477. magFilter = gl.NEAREST;
  7478. if (generateMipMaps) {
  7479. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7480. }
  7481. else {
  7482. minFilter = gl.LINEAR;
  7483. }
  7484. break;
  7485. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7486. magFilter = gl.NEAREST;
  7487. if (generateMipMaps) {
  7488. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7489. }
  7490. else {
  7491. minFilter = gl.LINEAR;
  7492. }
  7493. break;
  7494. case BABYLON.Texture.NEAREST_LINEAR:
  7495. magFilter = gl.NEAREST;
  7496. minFilter = gl.LINEAR;
  7497. break;
  7498. case BABYLON.Texture.NEAREST_NEAREST:
  7499. magFilter = gl.NEAREST;
  7500. minFilter = gl.NEAREST;
  7501. break;
  7502. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7503. magFilter = gl.LINEAR;
  7504. if (generateMipMaps) {
  7505. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7506. }
  7507. else {
  7508. minFilter = gl.NEAREST;
  7509. }
  7510. break;
  7511. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7512. magFilter = gl.LINEAR;
  7513. if (generateMipMaps) {
  7514. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7515. }
  7516. else {
  7517. minFilter = gl.NEAREST;
  7518. }
  7519. break;
  7520. case BABYLON.Texture.LINEAR_LINEAR:
  7521. magFilter = gl.LINEAR;
  7522. minFilter = gl.LINEAR;
  7523. break;
  7524. case BABYLON.Texture.LINEAR_NEAREST:
  7525. magFilter = gl.LINEAR;
  7526. minFilter = gl.NEAREST;
  7527. break;
  7528. }
  7529. return {
  7530. min: minFilter,
  7531. mag: magFilter
  7532. };
  7533. };
  7534. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7535. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7536. var img;
  7537. var onload = function () {
  7538. loadedImages[index] = img;
  7539. loadedImages._internalCount++;
  7540. if (scene) {
  7541. scene._removePendingData(img);
  7542. }
  7543. if (loadedImages._internalCount === 6) {
  7544. onfinish(loadedImages);
  7545. }
  7546. };
  7547. var onerror = function (message, exception) {
  7548. if (scene) {
  7549. scene._removePendingData(img);
  7550. }
  7551. if (onErrorCallBack) {
  7552. onErrorCallBack(message, exception);
  7553. }
  7554. };
  7555. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7556. if (scene) {
  7557. scene._addPendingData(img);
  7558. }
  7559. };
  7560. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7561. if (onError === void 0) { onError = null; }
  7562. var loadedImages = [];
  7563. loadedImages._internalCount = 0;
  7564. for (var index = 0; index < 6; index++) {
  7565. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7566. }
  7567. };
  7568. var BufferPointer = (function () {
  7569. function BufferPointer() {
  7570. }
  7571. return BufferPointer;
  7572. }());
  7573. var InstancingAttributeInfo = (function () {
  7574. function InstancingAttributeInfo() {
  7575. }
  7576. return InstancingAttributeInfo;
  7577. }());
  7578. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7579. /**
  7580. * Define options used to create a render target texture
  7581. */
  7582. var RenderTargetCreationOptions = (function () {
  7583. function RenderTargetCreationOptions() {
  7584. }
  7585. return RenderTargetCreationOptions;
  7586. }());
  7587. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7588. /**
  7589. * Regroup several parameters relative to the browser in use
  7590. */
  7591. var EngineCapabilities = (function () {
  7592. function EngineCapabilities() {
  7593. }
  7594. return EngineCapabilities;
  7595. }());
  7596. BABYLON.EngineCapabilities = EngineCapabilities;
  7597. /**
  7598. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7599. */
  7600. var Engine = (function () {
  7601. /**
  7602. * @constructor
  7603. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7604. * @param {boolean} [antialias] - enable antialias
  7605. * @param options - further options to be sent to the getContext function
  7606. */
  7607. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7608. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7609. var _this = this;
  7610. // Public members
  7611. this.forcePOTTextures = false;
  7612. this.isFullscreen = false;
  7613. this.isPointerLock = false;
  7614. this.cullBackFaces = true;
  7615. this.renderEvenInBackground = true;
  7616. this.preventCacheWipeBetweenFrames = false;
  7617. // To enable/disable IDB support and avoid XHR on .manifest
  7618. this.enableOfflineSupport = false;
  7619. this.scenes = new Array();
  7620. this.postProcesses = new Array();
  7621. // Observables
  7622. /**
  7623. * Observable event triggered each time the rendering canvas is resized
  7624. */
  7625. this.onResizeObservable = new BABYLON.Observable();
  7626. /**
  7627. * Observable event triggered each time the canvas loses focus
  7628. */
  7629. this.onCanvasBlurObservable = new BABYLON.Observable();
  7630. /**
  7631. * Observable event triggered each time the canvas gains focus
  7632. */
  7633. this.onCanvasFocusObservable = new BABYLON.Observable();
  7634. /**
  7635. * Observable event triggered each time the canvas receives pointerout event
  7636. */
  7637. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7638. /**
  7639. * Observable event triggered before each texture is initialized
  7640. */
  7641. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7642. //WebVR
  7643. this._vrDisplay = undefined;
  7644. this._vrSupported = false;
  7645. this._vrExclusivePointerMode = false;
  7646. // Uniform buffers list
  7647. this.disableUniformBuffers = false;
  7648. this._uniformBuffers = new Array();
  7649. this._windowIsBackground = false;
  7650. this._webGLVersion = 1.0;
  7651. this._badOS = false;
  7652. this._badDesktopOS = false;
  7653. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7654. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7655. this.onVRRequestPresentStart = new BABYLON.Observable();
  7656. this._colorWrite = true;
  7657. this._drawCalls = new BABYLON.PerfCounter();
  7658. this._renderingQueueLaunched = false;
  7659. this._activeRenderLoops = [];
  7660. // Deterministic lockstepMaxSteps
  7661. this._deterministicLockstep = false;
  7662. this._lockstepMaxSteps = 4;
  7663. // Lost context
  7664. this.onContextLostObservable = new BABYLON.Observable();
  7665. this.onContextRestoredObservable = new BABYLON.Observable();
  7666. this._contextWasLost = false;
  7667. this._doNotHandleContextLost = false;
  7668. // FPS
  7669. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7670. this._fps = 60;
  7671. this._deltaTime = 0;
  7672. /**
  7673. * Turn this value on if you want to pause FPS computation when in background
  7674. */
  7675. this.disablePerformanceMonitorInBackground = false;
  7676. // States
  7677. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7678. this._stencilState = new BABYLON.Internals._StencilState();
  7679. this._alphaState = new BABYLON.Internals._AlphaState();
  7680. this._alphaMode = Engine.ALPHA_DISABLE;
  7681. // Cache
  7682. this._internalTexturesCache = new Array();
  7683. this._maxTextureChannels = 16;
  7684. this._activeTexturesCache = {};
  7685. this._compiledEffects = {};
  7686. this._vertexAttribArraysEnabled = [];
  7687. this._uintIndicesCurrentlySet = false;
  7688. this._currentBoundBuffer = new Array();
  7689. this._currentBufferPointers = new Array();
  7690. this._currentInstanceLocations = new Array();
  7691. this._currentInstanceBuffers = new Array();
  7692. this._vaoRecordInProgress = false;
  7693. this._mustWipeVertexAttributes = false;
  7694. // Hardware supported Compressed Textures
  7695. this._texturesSupported = new Array();
  7696. this._onVRFullScreenTriggered = function () {
  7697. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7698. //get the old size before we change
  7699. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7700. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7701. //get the width and height, change the render size
  7702. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7703. var width, height;
  7704. _this.setHardwareScalingLevel(1);
  7705. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7706. }
  7707. else {
  7708. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7709. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7710. }
  7711. };
  7712. var canvas;
  7713. Engine.Instances.push(this);
  7714. options = options || {};
  7715. if (canvasOrContext.getContext) {
  7716. canvas = canvasOrContext;
  7717. this._renderingCanvas = canvas;
  7718. if (antialias != null) {
  7719. options.antialias = antialias;
  7720. }
  7721. if (options.deterministicLockstep === undefined) {
  7722. options.deterministicLockstep = false;
  7723. }
  7724. if (options.lockstepMaxSteps === undefined) {
  7725. options.lockstepMaxSteps = 4;
  7726. }
  7727. if (options.preserveDrawingBuffer === undefined) {
  7728. options.preserveDrawingBuffer = false;
  7729. }
  7730. if (options.audioEngine === undefined) {
  7731. options.audioEngine = true;
  7732. }
  7733. if (options.stencil === undefined) {
  7734. options.stencil = true;
  7735. }
  7736. this._deterministicLockstep = options.deterministicLockstep;
  7737. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7738. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7739. // GL
  7740. if (!options.disableWebGL2Support) {
  7741. try {
  7742. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7743. if (this._gl) {
  7744. this._webGLVersion = 2.0;
  7745. }
  7746. }
  7747. catch (e) {
  7748. // Do nothing
  7749. }
  7750. }
  7751. if (!this._gl) {
  7752. if (!canvas) {
  7753. throw new Error("The provided canvas is null or undefined.");
  7754. }
  7755. try {
  7756. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7757. }
  7758. catch (e) {
  7759. throw new Error("WebGL not supported");
  7760. }
  7761. }
  7762. if (!this._gl) {
  7763. throw new Error("WebGL not supported");
  7764. }
  7765. this._onCanvasFocus = function () {
  7766. _this.onCanvasFocusObservable.notifyObservers(_this);
  7767. };
  7768. this._onCanvasBlur = function () {
  7769. _this.onCanvasBlurObservable.notifyObservers(_this);
  7770. };
  7771. canvas.addEventListener("focus", this._onCanvasFocus);
  7772. canvas.addEventListener("blur", this._onCanvasBlur);
  7773. this._onBlur = function () {
  7774. if (_this.disablePerformanceMonitorInBackground) {
  7775. _this._performanceMonitor.disable();
  7776. }
  7777. _this._windowIsBackground = true;
  7778. };
  7779. this._onFocus = function () {
  7780. if (_this.disablePerformanceMonitorInBackground) {
  7781. _this._performanceMonitor.enable();
  7782. }
  7783. _this._windowIsBackground = false;
  7784. };
  7785. this._onCanvasPointerOut = function () {
  7786. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7787. };
  7788. window.addEventListener("blur", this._onBlur);
  7789. window.addEventListener("focus", this._onFocus);
  7790. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  7791. // Context lost
  7792. if (!this._doNotHandleContextLost) {
  7793. this._onContextLost = function (evt) {
  7794. evt.preventDefault();
  7795. _this._contextWasLost = true;
  7796. BABYLON.Tools.Warn("WebGL context lost.");
  7797. _this.onContextLostObservable.notifyObservers(_this);
  7798. };
  7799. this._onContextRestored = function (evt) {
  7800. // Adding a timeout to avoid race condition at browser level
  7801. setTimeout(function () {
  7802. // Rebuild gl context
  7803. _this._initGLContext();
  7804. // Rebuild effects
  7805. _this._rebuildEffects();
  7806. // Rebuild textures
  7807. _this._rebuildInternalTextures();
  7808. // Rebuild buffers
  7809. _this._rebuildBuffers();
  7810. // Cache
  7811. _this.wipeCaches(true);
  7812. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7813. _this.onContextRestoredObservable.notifyObservers(_this);
  7814. _this._contextWasLost = false;
  7815. }, 0);
  7816. };
  7817. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7818. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7819. }
  7820. }
  7821. else {
  7822. this._gl = canvasOrContext;
  7823. this._renderingCanvas = this._gl.canvas;
  7824. if (this._gl.renderbufferStorageMultisample) {
  7825. this._webGLVersion = 2.0;
  7826. }
  7827. options.stencil = this._gl.getContextAttributes().stencil;
  7828. }
  7829. // Viewport
  7830. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7831. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7832. this.resize();
  7833. this._isStencilEnable = options.stencil;
  7834. this._initGLContext();
  7835. if (canvas) {
  7836. // Fullscreen
  7837. this._onFullscreenChange = function () {
  7838. if (document.fullscreen !== undefined) {
  7839. _this.isFullscreen = document.fullscreen;
  7840. }
  7841. else if (document.mozFullScreen !== undefined) {
  7842. _this.isFullscreen = document.mozFullScreen;
  7843. }
  7844. else if (document.webkitIsFullScreen !== undefined) {
  7845. _this.isFullscreen = document.webkitIsFullScreen;
  7846. }
  7847. else if (document.msIsFullScreen !== undefined) {
  7848. _this.isFullscreen = document.msIsFullScreen;
  7849. }
  7850. // Pointer lock
  7851. if (_this.isFullscreen && _this._pointerLockRequested) {
  7852. canvas.requestPointerLock = canvas.requestPointerLock ||
  7853. canvas.msRequestPointerLock ||
  7854. canvas.mozRequestPointerLock ||
  7855. canvas.webkitRequestPointerLock;
  7856. if (canvas.requestPointerLock) {
  7857. canvas.requestPointerLock();
  7858. }
  7859. }
  7860. };
  7861. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7862. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7863. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7864. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7865. // Pointer lock
  7866. this._onPointerLockChange = function () {
  7867. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7868. document.webkitPointerLockElement === canvas ||
  7869. document.msPointerLockElement === canvas ||
  7870. document.pointerLockElement === canvas);
  7871. };
  7872. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7873. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7874. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7875. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7876. this._onVRDisplayPointerRestricted = function () {
  7877. canvas.requestPointerLock();
  7878. };
  7879. this._onVRDisplayPointerUnrestricted = function () {
  7880. document.exitPointerLock();
  7881. };
  7882. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7883. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7884. }
  7885. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7886. Engine.audioEngine = new BABYLON.AudioEngine();
  7887. }
  7888. // Prepare buffer pointers
  7889. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7890. this._currentBufferPointers[i] = new BufferPointer();
  7891. }
  7892. // Load WebVR Devices
  7893. if (options.autoEnableWebVR) {
  7894. this.initWebVR();
  7895. }
  7896. // Detect if we are running on a faulty buggy OS.
  7897. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7898. // Detect if we are running on a faulty buggy desktop OS.
  7899. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7900. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7901. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7902. }
  7903. Object.defineProperty(Engine, "LastCreatedEngine", {
  7904. get: function () {
  7905. if (Engine.Instances.length === 0) {
  7906. return null;
  7907. }
  7908. return Engine.Instances[Engine.Instances.length - 1];
  7909. },
  7910. enumerable: true,
  7911. configurable: true
  7912. });
  7913. Object.defineProperty(Engine, "LastCreatedScene", {
  7914. get: function () {
  7915. var lastCreatedEngine = Engine.LastCreatedEngine;
  7916. if (!lastCreatedEngine) {
  7917. return null;
  7918. }
  7919. if (lastCreatedEngine.scenes.length === 0) {
  7920. return null;
  7921. }
  7922. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7923. },
  7924. enumerable: true,
  7925. configurable: true
  7926. });
  7927. /**
  7928. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7929. */
  7930. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7931. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7932. var engine = Engine.Instances[engineIndex];
  7933. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7934. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7935. }
  7936. }
  7937. };
  7938. Object.defineProperty(Engine, "NEVER", {
  7939. get: function () {
  7940. return Engine._NEVER;
  7941. },
  7942. enumerable: true,
  7943. configurable: true
  7944. });
  7945. Object.defineProperty(Engine, "ALWAYS", {
  7946. get: function () {
  7947. return Engine._ALWAYS;
  7948. },
  7949. enumerable: true,
  7950. configurable: true
  7951. });
  7952. Object.defineProperty(Engine, "LESS", {
  7953. get: function () {
  7954. return Engine._LESS;
  7955. },
  7956. enumerable: true,
  7957. configurable: true
  7958. });
  7959. Object.defineProperty(Engine, "EQUAL", {
  7960. get: function () {
  7961. return Engine._EQUAL;
  7962. },
  7963. enumerable: true,
  7964. configurable: true
  7965. });
  7966. Object.defineProperty(Engine, "LEQUAL", {
  7967. get: function () {
  7968. return Engine._LEQUAL;
  7969. },
  7970. enumerable: true,
  7971. configurable: true
  7972. });
  7973. Object.defineProperty(Engine, "GREATER", {
  7974. get: function () {
  7975. return Engine._GREATER;
  7976. },
  7977. enumerable: true,
  7978. configurable: true
  7979. });
  7980. Object.defineProperty(Engine, "GEQUAL", {
  7981. get: function () {
  7982. return Engine._GEQUAL;
  7983. },
  7984. enumerable: true,
  7985. configurable: true
  7986. });
  7987. Object.defineProperty(Engine, "NOTEQUAL", {
  7988. get: function () {
  7989. return Engine._NOTEQUAL;
  7990. },
  7991. enumerable: true,
  7992. configurable: true
  7993. });
  7994. Object.defineProperty(Engine, "KEEP", {
  7995. get: function () {
  7996. return Engine._KEEP;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. Object.defineProperty(Engine, "REPLACE", {
  8002. get: function () {
  8003. return Engine._REPLACE;
  8004. },
  8005. enumerable: true,
  8006. configurable: true
  8007. });
  8008. Object.defineProperty(Engine, "INCR", {
  8009. get: function () {
  8010. return Engine._INCR;
  8011. },
  8012. enumerable: true,
  8013. configurable: true
  8014. });
  8015. Object.defineProperty(Engine, "DECR", {
  8016. get: function () {
  8017. return Engine._DECR;
  8018. },
  8019. enumerable: true,
  8020. configurable: true
  8021. });
  8022. Object.defineProperty(Engine, "INVERT", {
  8023. get: function () {
  8024. return Engine._INVERT;
  8025. },
  8026. enumerable: true,
  8027. configurable: true
  8028. });
  8029. Object.defineProperty(Engine, "INCR_WRAP", {
  8030. get: function () {
  8031. return Engine._INCR_WRAP;
  8032. },
  8033. enumerable: true,
  8034. configurable: true
  8035. });
  8036. Object.defineProperty(Engine, "DECR_WRAP", {
  8037. get: function () {
  8038. return Engine._DECR_WRAP;
  8039. },
  8040. enumerable: true,
  8041. configurable: true
  8042. });
  8043. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8044. get: function () {
  8045. return Engine._ALPHA_DISABLE;
  8046. },
  8047. enumerable: true,
  8048. configurable: true
  8049. });
  8050. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8051. get: function () {
  8052. return Engine._ALPHA_ONEONE;
  8053. },
  8054. enumerable: true,
  8055. configurable: true
  8056. });
  8057. Object.defineProperty(Engine, "ALPHA_ADD", {
  8058. get: function () {
  8059. return Engine._ALPHA_ADD;
  8060. },
  8061. enumerable: true,
  8062. configurable: true
  8063. });
  8064. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8065. get: function () {
  8066. return Engine._ALPHA_COMBINE;
  8067. },
  8068. enumerable: true,
  8069. configurable: true
  8070. });
  8071. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8072. get: function () {
  8073. return Engine._ALPHA_SUBTRACT;
  8074. },
  8075. enumerable: true,
  8076. configurable: true
  8077. });
  8078. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8079. get: function () {
  8080. return Engine._ALPHA_MULTIPLY;
  8081. },
  8082. enumerable: true,
  8083. configurable: true
  8084. });
  8085. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8086. get: function () {
  8087. return Engine._ALPHA_MAXIMIZED;
  8088. },
  8089. enumerable: true,
  8090. configurable: true
  8091. });
  8092. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8093. get: function () {
  8094. return Engine._ALPHA_PREMULTIPLIED;
  8095. },
  8096. enumerable: true,
  8097. configurable: true
  8098. });
  8099. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8100. get: function () {
  8101. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8102. },
  8103. enumerable: true,
  8104. configurable: true
  8105. });
  8106. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8107. get: function () {
  8108. return Engine._ALPHA_INTERPOLATE;
  8109. },
  8110. enumerable: true,
  8111. configurable: true
  8112. });
  8113. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8114. get: function () {
  8115. return Engine._ALPHA_SCREENMODE;
  8116. },
  8117. enumerable: true,
  8118. configurable: true
  8119. });
  8120. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8121. get: function () {
  8122. return Engine._DELAYLOADSTATE_NONE;
  8123. },
  8124. enumerable: true,
  8125. configurable: true
  8126. });
  8127. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8128. get: function () {
  8129. return Engine._DELAYLOADSTATE_LOADED;
  8130. },
  8131. enumerable: true,
  8132. configurable: true
  8133. });
  8134. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8135. get: function () {
  8136. return Engine._DELAYLOADSTATE_LOADING;
  8137. },
  8138. enumerable: true,
  8139. configurable: true
  8140. });
  8141. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8142. get: function () {
  8143. return Engine._DELAYLOADSTATE_NOTLOADED;
  8144. },
  8145. enumerable: true,
  8146. configurable: true
  8147. });
  8148. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8149. get: function () {
  8150. return Engine._TEXTUREFORMAT_ALPHA;
  8151. },
  8152. enumerable: true,
  8153. configurable: true
  8154. });
  8155. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8156. get: function () {
  8157. return Engine._TEXTUREFORMAT_LUMINANCE;
  8158. },
  8159. enumerable: true,
  8160. configurable: true
  8161. });
  8162. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8163. get: function () {
  8164. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8165. },
  8166. enumerable: true,
  8167. configurable: true
  8168. });
  8169. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8170. get: function () {
  8171. return Engine._TEXTUREFORMAT_RGB;
  8172. },
  8173. enumerable: true,
  8174. configurable: true
  8175. });
  8176. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8177. get: function () {
  8178. return Engine._TEXTUREFORMAT_RGBA;
  8179. },
  8180. enumerable: true,
  8181. configurable: true
  8182. });
  8183. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8184. get: function () {
  8185. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8186. },
  8187. enumerable: true,
  8188. configurable: true
  8189. });
  8190. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8191. get: function () {
  8192. return Engine._TEXTURETYPE_FLOAT;
  8193. },
  8194. enumerable: true,
  8195. configurable: true
  8196. });
  8197. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8198. get: function () {
  8199. return Engine._TEXTURETYPE_HALF_FLOAT;
  8200. },
  8201. enumerable: true,
  8202. configurable: true
  8203. });
  8204. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8205. get: function () {
  8206. return Engine._SCALEMODE_FLOOR;
  8207. },
  8208. enumerable: true,
  8209. configurable: true
  8210. });
  8211. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8212. get: function () {
  8213. return Engine._SCALEMODE_NEAREST;
  8214. },
  8215. enumerable: true,
  8216. configurable: true
  8217. });
  8218. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8219. get: function () {
  8220. return Engine._SCALEMODE_CEILING;
  8221. },
  8222. enumerable: true,
  8223. configurable: true
  8224. });
  8225. Object.defineProperty(Engine, "Version", {
  8226. get: function () {
  8227. return "3.1-alpha";
  8228. },
  8229. enumerable: true,
  8230. configurable: true
  8231. });
  8232. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8233. get: function () {
  8234. return this._vrExclusivePointerMode;
  8235. },
  8236. enumerable: true,
  8237. configurable: true
  8238. });
  8239. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8240. get: function () {
  8241. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8242. },
  8243. enumerable: true,
  8244. configurable: true
  8245. });
  8246. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8247. get: function () {
  8248. return this._webGLVersion < 2 || this.forcePOTTextures;
  8249. },
  8250. enumerable: true,
  8251. configurable: true
  8252. });
  8253. Object.defineProperty(Engine.prototype, "badOS", {
  8254. get: function () {
  8255. return this._badOS;
  8256. },
  8257. enumerable: true,
  8258. configurable: true
  8259. });
  8260. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8261. get: function () {
  8262. return this._badDesktopOS;
  8263. },
  8264. enumerable: true,
  8265. configurable: true
  8266. });
  8267. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8268. get: function () {
  8269. return this._performanceMonitor;
  8270. },
  8271. enumerable: true,
  8272. configurable: true
  8273. });
  8274. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8275. get: function () {
  8276. return this._texturesSupported;
  8277. },
  8278. enumerable: true,
  8279. configurable: true
  8280. });
  8281. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8282. get: function () {
  8283. return this._textureFormatInUse;
  8284. },
  8285. enumerable: true,
  8286. configurable: true
  8287. });
  8288. Object.defineProperty(Engine.prototype, "currentViewport", {
  8289. get: function () {
  8290. return this._cachedViewport;
  8291. },
  8292. enumerable: true,
  8293. configurable: true
  8294. });
  8295. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8296. // Empty texture
  8297. get: function () {
  8298. if (!this._emptyTexture) {
  8299. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8300. }
  8301. return this._emptyTexture;
  8302. },
  8303. enumerable: true,
  8304. configurable: true
  8305. });
  8306. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8307. get: function () {
  8308. if (!this._emptyCubeTexture) {
  8309. var faceData = new Uint8Array(4);
  8310. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8311. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8312. }
  8313. return this._emptyCubeTexture;
  8314. },
  8315. enumerable: true,
  8316. configurable: true
  8317. });
  8318. Engine.prototype._rebuildInternalTextures = function () {
  8319. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8320. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8321. var internalTexture = currentState_1[_i];
  8322. internalTexture._rebuild();
  8323. }
  8324. };
  8325. Engine.prototype._rebuildEffects = function () {
  8326. for (var key in this._compiledEffects) {
  8327. var effect = this._compiledEffects[key];
  8328. effect._prepareEffect();
  8329. }
  8330. BABYLON.Effect.ResetCache();
  8331. };
  8332. Engine.prototype._rebuildBuffers = function () {
  8333. // Index / Vertex
  8334. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8335. var scene = _a[_i];
  8336. scene.resetCachedMaterial();
  8337. scene._rebuildGeometries();
  8338. scene._rebuildTextures();
  8339. }
  8340. // Uniforms
  8341. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8342. var uniformBuffer = _c[_b];
  8343. uniformBuffer._rebuild();
  8344. }
  8345. };
  8346. Engine.prototype._initGLContext = function () {
  8347. // Caps
  8348. this._caps = new EngineCapabilities();
  8349. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8350. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8351. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8352. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8353. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8354. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8355. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8356. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8357. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8358. // Infos
  8359. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8360. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8361. if (rendererInfo != null) {
  8362. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8363. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8364. }
  8365. if (!this._glVendor) {
  8366. this._glVendor = "Unknown vendor";
  8367. }
  8368. if (!this._glRenderer) {
  8369. this._glRenderer = "Unknown renderer";
  8370. }
  8371. // Constants
  8372. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8373. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8374. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8375. this._gl.DEPTH24_STENCIL8 = 35056;
  8376. // Extensions
  8377. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8378. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8379. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8380. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8381. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8382. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8383. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8384. 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');
  8385. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8386. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8387. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8388. this._caps.highPrecisionShaderSupported = true;
  8389. // Checks if some of the format renders first to allow the use of webgl inspector.
  8390. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8391. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8392. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8393. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8394. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8395. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8396. if (this._webGLVersion > 1) {
  8397. this._gl.HALF_FLOAT_OES = 0x140B;
  8398. }
  8399. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8400. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8401. // Draw buffers
  8402. if (this._webGLVersion > 1) {
  8403. this._caps.drawBuffersExtension = true;
  8404. }
  8405. else {
  8406. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8407. if (drawBuffersExtension !== null) {
  8408. this._caps.drawBuffersExtension = true;
  8409. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8410. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8411. for (var i = 0; i < 16; i++) {
  8412. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8413. }
  8414. }
  8415. else {
  8416. this._caps.drawBuffersExtension = false;
  8417. }
  8418. }
  8419. // Depth Texture
  8420. if (this._webGLVersion > 1) {
  8421. this._caps.depthTextureExtension = true;
  8422. }
  8423. else {
  8424. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8425. if (depthTextureExtension != null) {
  8426. this._caps.depthTextureExtension = true;
  8427. }
  8428. }
  8429. // Vertex array object
  8430. if (this._webGLVersion > 1) {
  8431. this._caps.vertexArrayObject = true;
  8432. }
  8433. else {
  8434. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8435. if (vertexArrayObjectExtension != null) {
  8436. this._caps.vertexArrayObject = true;
  8437. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8438. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8439. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8440. }
  8441. else {
  8442. this._caps.vertexArrayObject = false;
  8443. }
  8444. }
  8445. // Instances count
  8446. if (this._webGLVersion > 1) {
  8447. this._caps.instancedArrays = true;
  8448. }
  8449. else {
  8450. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8451. if (instanceExtension != null) {
  8452. this._caps.instancedArrays = true;
  8453. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8454. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8455. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8456. }
  8457. else {
  8458. this._caps.instancedArrays = false;
  8459. }
  8460. }
  8461. // Intelligently add supported compressed formats in order to check for.
  8462. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8463. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8464. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8465. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8466. if (this._caps.astc)
  8467. this.texturesSupported.push('-astc.ktx');
  8468. if (this._caps.s3tc)
  8469. this.texturesSupported.push('-dxt.ktx');
  8470. if (this._caps.pvrtc)
  8471. this.texturesSupported.push('-pvrtc.ktx');
  8472. if (this._caps.etc2)
  8473. this.texturesSupported.push('-etc2.ktx');
  8474. if (this._caps.etc1)
  8475. this.texturesSupported.push('-etc1.ktx');
  8476. if (this._gl.getShaderPrecisionFormat) {
  8477. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8478. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8479. }
  8480. // Depth buffer
  8481. this.setDepthBuffer(true);
  8482. this.setDepthFunctionToLessOrEqual();
  8483. this.setDepthWrite(true);
  8484. };
  8485. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8486. get: function () {
  8487. return this._webGLVersion;
  8488. },
  8489. enumerable: true,
  8490. configurable: true
  8491. });
  8492. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8493. /**
  8494. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8495. */
  8496. get: function () {
  8497. return this._isStencilEnable;
  8498. },
  8499. enumerable: true,
  8500. configurable: true
  8501. });
  8502. Engine.prototype._prepareWorkingCanvas = function () {
  8503. if (this._workingCanvas) {
  8504. return;
  8505. }
  8506. this._workingCanvas = document.createElement("canvas");
  8507. this._workingContext = this._workingCanvas.getContext("2d");
  8508. };
  8509. Engine.prototype.resetTextureCache = function () {
  8510. for (var key in this._activeTexturesCache) {
  8511. this._activeTexturesCache[key] = null;
  8512. }
  8513. };
  8514. Engine.prototype.isDeterministicLockStep = function () {
  8515. return this._deterministicLockstep;
  8516. };
  8517. Engine.prototype.getLockstepMaxSteps = function () {
  8518. return this._lockstepMaxSteps;
  8519. };
  8520. Engine.prototype.getGlInfo = function () {
  8521. return {
  8522. vendor: this._glVendor,
  8523. renderer: this._glRenderer,
  8524. version: this._glVersion
  8525. };
  8526. };
  8527. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8528. if (useScreen === void 0) { useScreen = false; }
  8529. var viewport = camera.viewport;
  8530. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8531. };
  8532. Engine.prototype.getRenderWidth = function (useScreen) {
  8533. if (useScreen === void 0) { useScreen = false; }
  8534. if (!useScreen && this._currentRenderTarget) {
  8535. return this._currentRenderTarget.width;
  8536. }
  8537. return this._gl.drawingBufferWidth;
  8538. };
  8539. Engine.prototype.getRenderHeight = function (useScreen) {
  8540. if (useScreen === void 0) { useScreen = false; }
  8541. if (!useScreen && this._currentRenderTarget) {
  8542. return this._currentRenderTarget.height;
  8543. }
  8544. return this._gl.drawingBufferHeight;
  8545. };
  8546. Engine.prototype.getRenderingCanvas = function () {
  8547. return this._renderingCanvas;
  8548. };
  8549. Engine.prototype.getRenderingCanvasClientRect = function () {
  8550. return this._renderingCanvas.getBoundingClientRect();
  8551. };
  8552. Engine.prototype.setHardwareScalingLevel = function (level) {
  8553. this._hardwareScalingLevel = level;
  8554. this.resize();
  8555. };
  8556. Engine.prototype.getHardwareScalingLevel = function () {
  8557. return this._hardwareScalingLevel;
  8558. };
  8559. Engine.prototype.getLoadedTexturesCache = function () {
  8560. return this._internalTexturesCache;
  8561. };
  8562. Engine.prototype.getCaps = function () {
  8563. return this._caps;
  8564. };
  8565. Object.defineProperty(Engine.prototype, "drawCalls", {
  8566. /** The number of draw calls submitted last frame */
  8567. get: function () {
  8568. return this._drawCalls.current;
  8569. },
  8570. enumerable: true,
  8571. configurable: true
  8572. });
  8573. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8574. get: function () {
  8575. return this._drawCalls;
  8576. },
  8577. enumerable: true,
  8578. configurable: true
  8579. });
  8580. Engine.prototype.getDepthFunction = function () {
  8581. return this._depthCullingState.depthFunc;
  8582. };
  8583. Engine.prototype.setDepthFunction = function (depthFunc) {
  8584. this._depthCullingState.depthFunc = depthFunc;
  8585. };
  8586. Engine.prototype.setDepthFunctionToGreater = function () {
  8587. this._depthCullingState.depthFunc = this._gl.GREATER;
  8588. };
  8589. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8590. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8591. };
  8592. Engine.prototype.setDepthFunctionToLess = function () {
  8593. this._depthCullingState.depthFunc = this._gl.LESS;
  8594. };
  8595. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8596. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8597. };
  8598. Engine.prototype.getStencilBuffer = function () {
  8599. return this._stencilState.stencilTest;
  8600. };
  8601. Engine.prototype.setStencilBuffer = function (enable) {
  8602. this._stencilState.stencilTest = enable;
  8603. };
  8604. Engine.prototype.getStencilMask = function () {
  8605. return this._stencilState.stencilMask;
  8606. };
  8607. Engine.prototype.setStencilMask = function (mask) {
  8608. this._stencilState.stencilMask = mask;
  8609. };
  8610. Engine.prototype.getStencilFunction = function () {
  8611. return this._stencilState.stencilFunc;
  8612. };
  8613. Engine.prototype.getStencilFunctionReference = function () {
  8614. return this._stencilState.stencilFuncRef;
  8615. };
  8616. Engine.prototype.getStencilFunctionMask = function () {
  8617. return this._stencilState.stencilFuncMask;
  8618. };
  8619. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8620. this._stencilState.stencilFunc = stencilFunc;
  8621. };
  8622. Engine.prototype.setStencilFunctionReference = function (reference) {
  8623. this._stencilState.stencilFuncRef = reference;
  8624. };
  8625. Engine.prototype.setStencilFunctionMask = function (mask) {
  8626. this._stencilState.stencilFuncMask = mask;
  8627. };
  8628. Engine.prototype.getStencilOperationFail = function () {
  8629. return this._stencilState.stencilOpStencilFail;
  8630. };
  8631. Engine.prototype.getStencilOperationDepthFail = function () {
  8632. return this._stencilState.stencilOpDepthFail;
  8633. };
  8634. Engine.prototype.getStencilOperationPass = function () {
  8635. return this._stencilState.stencilOpStencilDepthPass;
  8636. };
  8637. Engine.prototype.setStencilOperationFail = function (operation) {
  8638. this._stencilState.stencilOpStencilFail = operation;
  8639. };
  8640. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8641. this._stencilState.stencilOpDepthFail = operation;
  8642. };
  8643. Engine.prototype.setStencilOperationPass = function (operation) {
  8644. this._stencilState.stencilOpStencilDepthPass = operation;
  8645. };
  8646. Engine.prototype.setDitheringState = function (value) {
  8647. if (value) {
  8648. this._gl.enable(this._gl.DITHER);
  8649. }
  8650. else {
  8651. this._gl.disable(this._gl.DITHER);
  8652. }
  8653. };
  8654. /**
  8655. * stop executing a render loop function and remove it from the execution array
  8656. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8657. */
  8658. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8659. if (!renderFunction) {
  8660. this._activeRenderLoops = [];
  8661. return;
  8662. }
  8663. var index = this._activeRenderLoops.indexOf(renderFunction);
  8664. if (index >= 0) {
  8665. this._activeRenderLoops.splice(index, 1);
  8666. }
  8667. };
  8668. Engine.prototype._renderLoop = function () {
  8669. if (!this._contextWasLost) {
  8670. var shouldRender = true;
  8671. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8672. shouldRender = false;
  8673. }
  8674. if (shouldRender) {
  8675. // Start new frame
  8676. this.beginFrame();
  8677. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8678. var renderFunction = this._activeRenderLoops[index];
  8679. renderFunction();
  8680. }
  8681. // Present
  8682. this.endFrame();
  8683. }
  8684. }
  8685. if (this._activeRenderLoops.length > 0) {
  8686. // Register new frame
  8687. var requester = window;
  8688. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8689. requester = this._vrDisplay;
  8690. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8691. }
  8692. else {
  8693. this._renderingQueueLaunched = false;
  8694. }
  8695. };
  8696. /**
  8697. * Register and execute a render loop. The engine can have more than one render function.
  8698. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8699. * @example
  8700. * engine.runRenderLoop(function () {
  8701. * scene.render()
  8702. * })
  8703. */
  8704. Engine.prototype.runRenderLoop = function (renderFunction) {
  8705. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8706. return;
  8707. }
  8708. this._activeRenderLoops.push(renderFunction);
  8709. if (!this._renderingQueueLaunched) {
  8710. this._renderingQueueLaunched = true;
  8711. this._bindedRenderFunction = this._renderLoop.bind(this);
  8712. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8713. }
  8714. };
  8715. /**
  8716. * Toggle full screen mode.
  8717. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8718. * @param {any} options - an options object to be sent to the requestFullscreen function
  8719. */
  8720. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8721. if (this.isFullscreen) {
  8722. BABYLON.Tools.ExitFullscreen();
  8723. }
  8724. else {
  8725. this._pointerLockRequested = requestPointerLock;
  8726. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8727. }
  8728. };
  8729. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8730. if (stencil === void 0) { stencil = false; }
  8731. this.applyStates();
  8732. var mode = 0;
  8733. if (backBuffer && color) {
  8734. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8735. mode |= this._gl.COLOR_BUFFER_BIT;
  8736. }
  8737. if (depth) {
  8738. this._gl.clearDepth(1.0);
  8739. mode |= this._gl.DEPTH_BUFFER_BIT;
  8740. }
  8741. if (stencil) {
  8742. this._gl.clearStencil(0);
  8743. mode |= this._gl.STENCIL_BUFFER_BIT;
  8744. }
  8745. this._gl.clear(mode);
  8746. };
  8747. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8748. var gl = this._gl;
  8749. // Save state
  8750. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8751. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8752. // Change state
  8753. gl.enable(gl.SCISSOR_TEST);
  8754. gl.scissor(x, y, width, height);
  8755. // Clear
  8756. this.clear(clearColor, true, true, true);
  8757. // Restore state
  8758. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8759. if (curScissor === true) {
  8760. gl.enable(gl.SCISSOR_TEST);
  8761. }
  8762. else {
  8763. gl.disable(gl.SCISSOR_TEST);
  8764. }
  8765. };
  8766. /**
  8767. * Set the WebGL's viewport
  8768. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8769. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8770. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8771. */
  8772. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8773. var width = requiredWidth || this.getRenderWidth();
  8774. var height = requiredHeight || this.getRenderHeight();
  8775. var x = viewport.x || 0;
  8776. var y = viewport.y || 0;
  8777. this._cachedViewport = viewport;
  8778. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8779. };
  8780. /**
  8781. * Directly set the WebGL Viewport
  8782. * The x, y, width & height are directly passed to the WebGL call
  8783. * @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.
  8784. */
  8785. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8786. var currentViewport = this._cachedViewport;
  8787. this._cachedViewport = null;
  8788. this._gl.viewport(x, y, width, height);
  8789. return currentViewport;
  8790. };
  8791. Engine.prototype.beginFrame = function () {
  8792. this._measureFps();
  8793. };
  8794. Engine.prototype.endFrame = function () {
  8795. //force a flush in case we are using a bad OS.
  8796. if (this._badOS) {
  8797. this.flushFramebuffer();
  8798. }
  8799. //submit frame to the vr device, if enabled
  8800. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  8801. // TODO: We should only submit the frame if we read frameData successfully.
  8802. this._vrDisplay.submitFrame();
  8803. }
  8804. };
  8805. /**
  8806. * resize the view according to the canvas' size.
  8807. * @example
  8808. * window.addEventListener("resize", function () {
  8809. * engine.resize();
  8810. * });
  8811. */
  8812. Engine.prototype.resize = function () {
  8813. // We're not resizing the size of the canvas while in VR mode & presenting
  8814. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  8815. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8816. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8817. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8818. }
  8819. };
  8820. /**
  8821. * force a specific size of the canvas
  8822. * @param {number} width - the new canvas' width
  8823. * @param {number} height - the new canvas' height
  8824. */
  8825. Engine.prototype.setSize = function (width, height) {
  8826. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8827. return;
  8828. }
  8829. this._renderingCanvas.width = width;
  8830. this._renderingCanvas.height = height;
  8831. for (var index = 0; index < this.scenes.length; index++) {
  8832. var scene = this.scenes[index];
  8833. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8834. var cam = scene.cameras[camIndex];
  8835. cam._currentRenderId = 0;
  8836. }
  8837. }
  8838. if (this.onResizeObservable.hasObservers) {
  8839. this.onResizeObservable.notifyObservers(this);
  8840. }
  8841. };
  8842. // WebVR functions
  8843. Engine.prototype.isVRDevicePresent = function () {
  8844. return !!this._vrDisplay;
  8845. };
  8846. Engine.prototype.getVRDevice = function () {
  8847. return this._vrDisplay;
  8848. };
  8849. Engine.prototype.initWebVR = function () {
  8850. var _this = this;
  8851. var notifyObservers = function () {
  8852. var eventArgs = {
  8853. vrDisplay: _this._vrDisplay,
  8854. vrSupported: _this._vrSupported
  8855. };
  8856. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  8857. };
  8858. if (!this._onVrDisplayConnect) {
  8859. this._onVrDisplayConnect = function (event) {
  8860. _this._vrDisplay = event.display;
  8861. notifyObservers();
  8862. };
  8863. this._onVrDisplayDisconnect = function () {
  8864. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  8865. _this._vrDisplay = undefined;
  8866. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  8867. notifyObservers();
  8868. };
  8869. this._onVrDisplayPresentChange = function () {
  8870. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  8871. };
  8872. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  8873. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  8874. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  8875. }
  8876. this._getVRDisplays(notifyObservers);
  8877. return this.onVRDisplayChangedObservable;
  8878. };
  8879. Engine.prototype.enableVR = function () {
  8880. var _this = this;
  8881. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  8882. var onResolved = function () {
  8883. _this.onVRRequestPresentComplete.notifyObservers(true);
  8884. _this._onVRFullScreenTriggered();
  8885. };
  8886. var onRejected = function () {
  8887. _this.onVRRequestPresentComplete.notifyObservers(false);
  8888. };
  8889. this.onVRRequestPresentStart.notifyObservers(this);
  8890. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  8891. }
  8892. };
  8893. Engine.prototype.disableVR = function () {
  8894. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  8895. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  8896. }
  8897. };
  8898. Engine.prototype._getVRDisplays = function (callback) {
  8899. var _this = this;
  8900. var getWebVRDevices = function (devices) {
  8901. _this._vrSupported = true;
  8902. // note that devices may actually be an empty array. This is fine;
  8903. // we expect this._vrDisplay to be undefined in this case.
  8904. return _this._vrDisplay = devices[0];
  8905. };
  8906. if (navigator.getVRDisplays) {
  8907. // TODO: Backwards compatible for 1.0?
  8908. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  8909. // TODO: System CANNOT support WebVR, despite API presence.
  8910. _this._vrSupported = false;
  8911. callback();
  8912. });
  8913. }
  8914. else {
  8915. // TODO: Browser does not support WebVR
  8916. this._vrDisplay = undefined;
  8917. this._vrSupported = false;
  8918. callback();
  8919. }
  8920. };
  8921. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8922. if (this._currentRenderTarget) {
  8923. this.unBindFramebuffer(this._currentRenderTarget);
  8924. }
  8925. this._currentRenderTarget = texture;
  8926. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8927. var gl = this._gl;
  8928. if (texture.isCube) {
  8929. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8930. }
  8931. if (this._cachedViewport && !forceFullscreenViewport) {
  8932. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8933. }
  8934. else {
  8935. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8936. }
  8937. this.wipeCaches();
  8938. };
  8939. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8940. if (this._currentFramebuffer !== framebuffer) {
  8941. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8942. this._currentFramebuffer = framebuffer;
  8943. }
  8944. };
  8945. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8946. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8947. this._currentRenderTarget = null;
  8948. // If MSAA, we need to bitblt back to main texture
  8949. var gl = this._gl;
  8950. if (texture._MSAAFramebuffer) {
  8951. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8952. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8953. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8954. }
  8955. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8956. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8957. gl.generateMipmap(gl.TEXTURE_2D);
  8958. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8959. }
  8960. if (onBeforeUnbind) {
  8961. if (texture._MSAAFramebuffer) {
  8962. // Bind the correct framebuffer
  8963. this.bindUnboundFramebuffer(texture._framebuffer);
  8964. }
  8965. onBeforeUnbind();
  8966. }
  8967. this.bindUnboundFramebuffer(null);
  8968. };
  8969. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8970. if (texture.generateMipMaps) {
  8971. var gl = this._gl;
  8972. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8973. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8974. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8975. }
  8976. };
  8977. Engine.prototype.flushFramebuffer = function () {
  8978. this._gl.flush();
  8979. };
  8980. Engine.prototype.restoreDefaultFramebuffer = function () {
  8981. if (this._currentRenderTarget) {
  8982. this.unBindFramebuffer(this._currentRenderTarget);
  8983. }
  8984. else {
  8985. this.bindUnboundFramebuffer(null);
  8986. }
  8987. if (this._cachedViewport) {
  8988. this.setViewport(this._cachedViewport);
  8989. }
  8990. this.wipeCaches();
  8991. };
  8992. // UBOs
  8993. Engine.prototype.createUniformBuffer = function (elements) {
  8994. var ubo = this._gl.createBuffer();
  8995. this.bindUniformBuffer(ubo);
  8996. if (elements instanceof Float32Array) {
  8997. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8998. }
  8999. else {
  9000. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9001. }
  9002. this.bindUniformBuffer(null);
  9003. ubo.references = 1;
  9004. return ubo;
  9005. };
  9006. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9007. var ubo = this._gl.createBuffer();
  9008. this.bindUniformBuffer(ubo);
  9009. if (elements instanceof Float32Array) {
  9010. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9011. }
  9012. else {
  9013. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9014. }
  9015. this.bindUniformBuffer(null);
  9016. ubo.references = 1;
  9017. return ubo;
  9018. };
  9019. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9020. this.bindUniformBuffer(uniformBuffer);
  9021. if (offset === undefined) {
  9022. offset = 0;
  9023. }
  9024. if (count === undefined) {
  9025. if (elements instanceof Float32Array) {
  9026. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9027. }
  9028. else {
  9029. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9030. }
  9031. }
  9032. else {
  9033. if (elements instanceof Float32Array) {
  9034. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9035. }
  9036. else {
  9037. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9038. }
  9039. }
  9040. this.bindUniformBuffer(null);
  9041. };
  9042. // VBOs
  9043. Engine.prototype._resetVertexBufferBinding = function () {
  9044. this.bindArrayBuffer(null);
  9045. this._cachedVertexBuffers = null;
  9046. };
  9047. Engine.prototype.createVertexBuffer = function (vertices) {
  9048. var vbo = this._gl.createBuffer();
  9049. this.bindArrayBuffer(vbo);
  9050. if (vertices instanceof Float32Array) {
  9051. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9052. }
  9053. else {
  9054. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9055. }
  9056. this._resetVertexBufferBinding();
  9057. vbo.references = 1;
  9058. return vbo;
  9059. };
  9060. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9061. var vbo = this._gl.createBuffer();
  9062. this.bindArrayBuffer(vbo);
  9063. if (vertices instanceof Float32Array) {
  9064. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9065. }
  9066. else {
  9067. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9068. }
  9069. this._resetVertexBufferBinding();
  9070. vbo.references = 1;
  9071. return vbo;
  9072. };
  9073. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9074. this.bindArrayBuffer(vertexBuffer);
  9075. if (offset === undefined) {
  9076. offset = 0;
  9077. }
  9078. if (count === undefined) {
  9079. if (vertices instanceof Float32Array) {
  9080. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9081. }
  9082. else {
  9083. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9084. }
  9085. }
  9086. else {
  9087. if (vertices instanceof Float32Array) {
  9088. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9089. }
  9090. else {
  9091. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9092. }
  9093. }
  9094. this._resetVertexBufferBinding();
  9095. };
  9096. Engine.prototype._resetIndexBufferBinding = function () {
  9097. this.bindIndexBuffer(null);
  9098. this._cachedIndexBuffer = null;
  9099. };
  9100. Engine.prototype.createIndexBuffer = function (indices) {
  9101. var vbo = this._gl.createBuffer();
  9102. this.bindIndexBuffer(vbo);
  9103. // Check for 32 bits indices
  9104. var arrayBuffer;
  9105. var need32Bits = false;
  9106. if (indices instanceof Uint16Array) {
  9107. arrayBuffer = indices;
  9108. }
  9109. else {
  9110. //check 32 bit support
  9111. if (this._caps.uintIndices) {
  9112. if (indices instanceof Uint32Array) {
  9113. arrayBuffer = indices;
  9114. need32Bits = true;
  9115. }
  9116. else {
  9117. //number[] or Int32Array, check if 32 bit is necessary
  9118. for (var index = 0; index < indices.length; index++) {
  9119. if (indices[index] > 65535) {
  9120. need32Bits = true;
  9121. break;
  9122. }
  9123. }
  9124. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9125. }
  9126. }
  9127. else {
  9128. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9129. arrayBuffer = new Uint16Array(indices);
  9130. }
  9131. }
  9132. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  9133. this._resetIndexBufferBinding();
  9134. vbo.references = 1;
  9135. vbo.is32Bits = need32Bits;
  9136. return vbo;
  9137. };
  9138. Engine.prototype.bindArrayBuffer = function (buffer) {
  9139. if (!this._vaoRecordInProgress) {
  9140. this._unbindVertexArrayObject();
  9141. }
  9142. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9143. };
  9144. Engine.prototype.bindUniformBuffer = function (buffer) {
  9145. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9146. };
  9147. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9148. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9149. };
  9150. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9151. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9152. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9153. };
  9154. ;
  9155. Engine.prototype.bindIndexBuffer = function (buffer) {
  9156. if (!this._vaoRecordInProgress) {
  9157. this._unbindVertexArrayObject();
  9158. }
  9159. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9160. };
  9161. Engine.prototype.bindBuffer = function (buffer, target) {
  9162. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9163. this._gl.bindBuffer(target, buffer);
  9164. this._currentBoundBuffer[target] = buffer;
  9165. }
  9166. };
  9167. Engine.prototype.updateArrayBuffer = function (data) {
  9168. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9169. };
  9170. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9171. var pointer = this._currentBufferPointers[indx];
  9172. var changed = false;
  9173. if (!pointer.active) {
  9174. changed = true;
  9175. pointer.active = true;
  9176. pointer.index = indx;
  9177. pointer.size = size;
  9178. pointer.type = type;
  9179. pointer.normalized = normalized;
  9180. pointer.stride = stride;
  9181. pointer.offset = offset;
  9182. pointer.buffer = buffer;
  9183. }
  9184. else {
  9185. if (pointer.buffer !== buffer) {
  9186. pointer.buffer = buffer;
  9187. changed = true;
  9188. }
  9189. if (pointer.size !== size) {
  9190. pointer.size = size;
  9191. changed = true;
  9192. }
  9193. if (pointer.type !== type) {
  9194. pointer.type = type;
  9195. changed = true;
  9196. }
  9197. if (pointer.normalized !== normalized) {
  9198. pointer.normalized = normalized;
  9199. changed = true;
  9200. }
  9201. if (pointer.stride !== stride) {
  9202. pointer.stride = stride;
  9203. changed = true;
  9204. }
  9205. if (pointer.offset !== offset) {
  9206. pointer.offset = offset;
  9207. changed = true;
  9208. }
  9209. }
  9210. if (changed || this._vaoRecordInProgress) {
  9211. this.bindArrayBuffer(buffer);
  9212. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9213. }
  9214. };
  9215. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9216. if (indexBuffer == null) {
  9217. return;
  9218. }
  9219. if (this._cachedIndexBuffer !== indexBuffer) {
  9220. this._cachedIndexBuffer = indexBuffer;
  9221. this.bindIndexBuffer(indexBuffer);
  9222. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9223. }
  9224. };
  9225. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9226. var attributes = effect.getAttributesNames();
  9227. if (!this._vaoRecordInProgress) {
  9228. this._unbindVertexArrayObject();
  9229. }
  9230. this.unbindAllAttributes();
  9231. for (var index = 0; index < attributes.length; index++) {
  9232. var order = effect.getAttributeLocation(index);
  9233. if (order >= 0) {
  9234. var vertexBuffer = vertexBuffers[attributes[index]];
  9235. if (!vertexBuffer) {
  9236. continue;
  9237. }
  9238. this._gl.enableVertexAttribArray(order);
  9239. if (!this._vaoRecordInProgress) {
  9240. this._vertexAttribArraysEnabled[order] = true;
  9241. }
  9242. var buffer = vertexBuffer.getBuffer();
  9243. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9244. if (vertexBuffer.getIsInstanced()) {
  9245. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9246. if (!this._vaoRecordInProgress) {
  9247. this._currentInstanceLocations.push(order);
  9248. this._currentInstanceBuffers.push(buffer);
  9249. }
  9250. }
  9251. }
  9252. }
  9253. };
  9254. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9255. var vao = this._gl.createVertexArray();
  9256. this._vaoRecordInProgress = true;
  9257. this._gl.bindVertexArray(vao);
  9258. this._mustWipeVertexAttributes = true;
  9259. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9260. this.bindIndexBuffer(indexBuffer);
  9261. this._vaoRecordInProgress = false;
  9262. this._gl.bindVertexArray(null);
  9263. return vao;
  9264. };
  9265. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9266. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9267. this._cachedVertexArrayObject = vertexArrayObject;
  9268. this._gl.bindVertexArray(vertexArrayObject);
  9269. this._cachedVertexBuffers = null;
  9270. this._cachedIndexBuffer = null;
  9271. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9272. this._mustWipeVertexAttributes = true;
  9273. }
  9274. };
  9275. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9276. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9277. this._cachedVertexBuffers = vertexBuffer;
  9278. this._cachedEffectForVertexBuffers = effect;
  9279. var attributesCount = effect.getAttributesCount();
  9280. this._unbindVertexArrayObject();
  9281. this.unbindAllAttributes();
  9282. var offset = 0;
  9283. for (var index = 0; index < attributesCount; index++) {
  9284. if (index < vertexDeclaration.length) {
  9285. var order = effect.getAttributeLocation(index);
  9286. if (order >= 0) {
  9287. this._gl.enableVertexAttribArray(order);
  9288. this._vertexAttribArraysEnabled[order] = true;
  9289. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9290. }
  9291. offset += vertexDeclaration[index] * 4;
  9292. }
  9293. }
  9294. }
  9295. this._bindIndexBufferWithCache(indexBuffer);
  9296. };
  9297. Engine.prototype._unbindVertexArrayObject = function () {
  9298. if (!this._cachedVertexArrayObject) {
  9299. return;
  9300. }
  9301. this._cachedVertexArrayObject = null;
  9302. this._gl.bindVertexArray(null);
  9303. };
  9304. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9305. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9306. this._cachedVertexBuffers = vertexBuffers;
  9307. this._cachedEffectForVertexBuffers = effect;
  9308. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9309. }
  9310. this._bindIndexBufferWithCache(indexBuffer);
  9311. };
  9312. Engine.prototype.unbindInstanceAttributes = function () {
  9313. var boundBuffer;
  9314. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9315. var instancesBuffer = this._currentInstanceBuffers[i];
  9316. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9317. boundBuffer = instancesBuffer;
  9318. this.bindArrayBuffer(instancesBuffer);
  9319. }
  9320. var offsetLocation = this._currentInstanceLocations[i];
  9321. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9322. }
  9323. this._currentInstanceBuffers.length = 0;
  9324. this._currentInstanceLocations.length = 0;
  9325. };
  9326. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9327. this._gl.deleteVertexArray(vao);
  9328. };
  9329. Engine.prototype._releaseBuffer = function (buffer) {
  9330. buffer.references--;
  9331. if (buffer.references === 0) {
  9332. this._gl.deleteBuffer(buffer);
  9333. return true;
  9334. }
  9335. return false;
  9336. };
  9337. Engine.prototype.createInstancesBuffer = function (capacity) {
  9338. var buffer = this._gl.createBuffer();
  9339. buffer.capacity = capacity;
  9340. this.bindArrayBuffer(buffer);
  9341. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9342. return buffer;
  9343. };
  9344. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9345. this._gl.deleteBuffer(buffer);
  9346. };
  9347. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9348. this.bindArrayBuffer(instancesBuffer);
  9349. if (data) {
  9350. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9351. }
  9352. if (offsetLocations[0].index !== undefined) {
  9353. var stride = 0;
  9354. for (var i = 0; i < offsetLocations.length; i++) {
  9355. var ai = offsetLocations[i];
  9356. stride += ai.attributeSize * 4;
  9357. }
  9358. for (var i = 0; i < offsetLocations.length; i++) {
  9359. var ai = offsetLocations[i];
  9360. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9361. this._gl.enableVertexAttribArray(ai.index);
  9362. this._vertexAttribArraysEnabled[ai.index] = true;
  9363. }
  9364. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9365. this._gl.vertexAttribDivisor(ai.index, 1);
  9366. this._currentInstanceLocations.push(ai.index);
  9367. this._currentInstanceBuffers.push(instancesBuffer);
  9368. }
  9369. }
  9370. else {
  9371. for (var index = 0; index < 4; index++) {
  9372. var offsetLocation = offsetLocations[index];
  9373. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9374. this._gl.enableVertexAttribArray(offsetLocation);
  9375. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9376. }
  9377. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9378. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9379. this._currentInstanceLocations.push(offsetLocation);
  9380. this._currentInstanceBuffers.push(instancesBuffer);
  9381. }
  9382. }
  9383. };
  9384. Engine.prototype.applyStates = function () {
  9385. this._depthCullingState.apply(this._gl);
  9386. this._stencilState.apply(this._gl);
  9387. this._alphaState.apply(this._gl);
  9388. };
  9389. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9390. // Apply states
  9391. this.applyStates();
  9392. this._drawCalls.addCount(1, false);
  9393. // Render
  9394. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9395. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9396. if (instancesCount) {
  9397. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9398. return;
  9399. }
  9400. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9401. };
  9402. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9403. // Apply states
  9404. this.applyStates();
  9405. this._drawCalls.addCount(1, false);
  9406. if (instancesCount) {
  9407. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9408. return;
  9409. }
  9410. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9411. };
  9412. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9413. // Apply states
  9414. this.applyStates();
  9415. this._drawCalls.addCount(1, false);
  9416. if (instancesCount) {
  9417. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9418. return;
  9419. }
  9420. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9421. };
  9422. // Shaders
  9423. Engine.prototype._releaseEffect = function (effect) {
  9424. if (this._compiledEffects[effect._key]) {
  9425. delete this._compiledEffects[effect._key];
  9426. if (effect.getProgram()) {
  9427. this._gl.deleteProgram(effect.getProgram());
  9428. }
  9429. }
  9430. };
  9431. /**
  9432. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9433. * @param samplers An array of string used to represent textures
  9434. */
  9435. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9436. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9437. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9438. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9439. if (this._compiledEffects[name]) {
  9440. var compiledEffect = this._compiledEffects[name];
  9441. if (onCompiled && compiledEffect.isReady()) {
  9442. onCompiled(compiledEffect);
  9443. }
  9444. return compiledEffect;
  9445. }
  9446. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9447. effect._key = name;
  9448. this._compiledEffects[name] = effect;
  9449. return effect;
  9450. };
  9451. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9452. if (uniformsNames === void 0) { uniformsNames = []; }
  9453. if (samplers === void 0) { samplers = []; }
  9454. if (defines === void 0) { defines = ""; }
  9455. return this.createEffect({
  9456. vertex: "particles",
  9457. fragmentElement: fragmentName
  9458. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9459. };
  9460. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9461. context = context || this._gl;
  9462. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9463. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9464. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9465. var shaderProgram = context.createProgram();
  9466. context.attachShader(shaderProgram, vertexShader);
  9467. context.attachShader(shaderProgram, fragmentShader);
  9468. context.linkProgram(shaderProgram);
  9469. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9470. if (!linked) {
  9471. context.validateProgram(shaderProgram);
  9472. var error = context.getProgramInfoLog(shaderProgram);
  9473. if (error) {
  9474. throw new Error(error);
  9475. }
  9476. }
  9477. context.deleteShader(vertexShader);
  9478. context.deleteShader(fragmentShader);
  9479. return shaderProgram;
  9480. };
  9481. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9482. var results = [];
  9483. for (var index = 0; index < uniformsNames.length; index++) {
  9484. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9485. }
  9486. return results;
  9487. };
  9488. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9489. var results = [];
  9490. for (var index = 0; index < attributesNames.length; index++) {
  9491. try {
  9492. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9493. }
  9494. catch (e) {
  9495. results.push(-1);
  9496. }
  9497. }
  9498. return results;
  9499. };
  9500. Engine.prototype.enableEffect = function (effect) {
  9501. // Use program
  9502. this.setProgram(effect.getProgram());
  9503. this._currentEffect = effect;
  9504. if (effect.onBind) {
  9505. effect.onBind(effect);
  9506. }
  9507. effect.onBindObservable.notifyObservers(effect);
  9508. };
  9509. Engine.prototype.setIntArray = function (uniform, array) {
  9510. if (!uniform)
  9511. return;
  9512. this._gl.uniform1iv(uniform, array);
  9513. };
  9514. Engine.prototype.setIntArray2 = function (uniform, array) {
  9515. if (!uniform || array.length % 2 !== 0)
  9516. return;
  9517. this._gl.uniform2iv(uniform, array);
  9518. };
  9519. Engine.prototype.setIntArray3 = function (uniform, array) {
  9520. if (!uniform || array.length % 3 !== 0)
  9521. return;
  9522. this._gl.uniform3iv(uniform, array);
  9523. };
  9524. Engine.prototype.setIntArray4 = function (uniform, array) {
  9525. if (!uniform || array.length % 4 !== 0)
  9526. return;
  9527. this._gl.uniform4iv(uniform, array);
  9528. };
  9529. Engine.prototype.setFloatArray = function (uniform, array) {
  9530. if (!uniform)
  9531. return;
  9532. this._gl.uniform1fv(uniform, array);
  9533. };
  9534. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9535. if (!uniform || array.length % 2 !== 0)
  9536. return;
  9537. this._gl.uniform2fv(uniform, array);
  9538. };
  9539. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9540. if (!uniform || array.length % 3 !== 0)
  9541. return;
  9542. this._gl.uniform3fv(uniform, array);
  9543. };
  9544. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9545. if (!uniform || array.length % 4 !== 0)
  9546. return;
  9547. this._gl.uniform4fv(uniform, array);
  9548. };
  9549. Engine.prototype.setArray = function (uniform, array) {
  9550. if (!uniform)
  9551. return;
  9552. this._gl.uniform1fv(uniform, array);
  9553. };
  9554. Engine.prototype.setArray2 = function (uniform, array) {
  9555. if (!uniform || array.length % 2 !== 0)
  9556. return;
  9557. this._gl.uniform2fv(uniform, array);
  9558. };
  9559. Engine.prototype.setArray3 = function (uniform, array) {
  9560. if (!uniform || array.length % 3 !== 0)
  9561. return;
  9562. this._gl.uniform3fv(uniform, array);
  9563. };
  9564. Engine.prototype.setArray4 = function (uniform, array) {
  9565. if (!uniform || array.length % 4 !== 0)
  9566. return;
  9567. this._gl.uniform4fv(uniform, array);
  9568. };
  9569. Engine.prototype.setMatrices = function (uniform, matrices) {
  9570. if (!uniform)
  9571. return;
  9572. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9573. };
  9574. Engine.prototype.setMatrix = function (uniform, matrix) {
  9575. if (!uniform)
  9576. return;
  9577. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9578. };
  9579. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9580. if (!uniform)
  9581. return;
  9582. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9583. };
  9584. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9585. if (!uniform)
  9586. return;
  9587. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9588. };
  9589. Engine.prototype.setFloat = function (uniform, value) {
  9590. if (!uniform)
  9591. return;
  9592. this._gl.uniform1f(uniform, value);
  9593. };
  9594. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9595. if (!uniform)
  9596. return;
  9597. this._gl.uniform2f(uniform, x, y);
  9598. };
  9599. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9600. if (!uniform)
  9601. return;
  9602. this._gl.uniform3f(uniform, x, y, z);
  9603. };
  9604. Engine.prototype.setBool = function (uniform, bool) {
  9605. if (!uniform)
  9606. return;
  9607. this._gl.uniform1i(uniform, bool);
  9608. };
  9609. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9610. if (!uniform)
  9611. return;
  9612. this._gl.uniform4f(uniform, x, y, z, w);
  9613. };
  9614. Engine.prototype.setColor3 = function (uniform, color3) {
  9615. if (!uniform)
  9616. return;
  9617. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9618. };
  9619. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9620. if (!uniform)
  9621. return;
  9622. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9623. };
  9624. // States
  9625. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9626. if (zOffset === void 0) { zOffset = 0; }
  9627. if (reverseSide === void 0) { reverseSide = false; }
  9628. // Culling
  9629. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9630. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9631. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9632. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9633. if (culling) {
  9634. this._depthCullingState.cullFace = cullFace;
  9635. this._depthCullingState.cull = true;
  9636. }
  9637. else {
  9638. this._depthCullingState.cull = false;
  9639. }
  9640. }
  9641. // Z offset
  9642. this.setZOffset(zOffset);
  9643. };
  9644. Engine.prototype.setZOffset = function (value) {
  9645. this._depthCullingState.zOffset = value;
  9646. };
  9647. Engine.prototype.getZOffset = function () {
  9648. return this._depthCullingState.zOffset;
  9649. };
  9650. Engine.prototype.setDepthBuffer = function (enable) {
  9651. this._depthCullingState.depthTest = enable;
  9652. };
  9653. Engine.prototype.getDepthWrite = function () {
  9654. return this._depthCullingState.depthMask;
  9655. };
  9656. Engine.prototype.setDepthWrite = function (enable) {
  9657. this._depthCullingState.depthMask = enable;
  9658. };
  9659. Engine.prototype.setColorWrite = function (enable) {
  9660. this._gl.colorMask(enable, enable, enable, enable);
  9661. this._colorWrite = enable;
  9662. };
  9663. Engine.prototype.getColorWrite = function () {
  9664. return this._colorWrite;
  9665. };
  9666. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9667. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9668. };
  9669. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9670. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9671. if (this._alphaMode === mode) {
  9672. return;
  9673. }
  9674. switch (mode) {
  9675. case Engine.ALPHA_DISABLE:
  9676. this._alphaState.alphaBlend = false;
  9677. break;
  9678. case Engine.ALPHA_PREMULTIPLIED:
  9679. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9680. this._alphaState.alphaBlend = true;
  9681. break;
  9682. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9683. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9684. this._alphaState.alphaBlend = true;
  9685. break;
  9686. case Engine.ALPHA_COMBINE:
  9687. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9688. this._alphaState.alphaBlend = true;
  9689. break;
  9690. case Engine.ALPHA_ONEONE:
  9691. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9692. this._alphaState.alphaBlend = true;
  9693. break;
  9694. case Engine.ALPHA_ADD:
  9695. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9696. this._alphaState.alphaBlend = true;
  9697. break;
  9698. case Engine.ALPHA_SUBTRACT:
  9699. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9700. this._alphaState.alphaBlend = true;
  9701. break;
  9702. case Engine.ALPHA_MULTIPLY:
  9703. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9704. this._alphaState.alphaBlend = true;
  9705. break;
  9706. case Engine.ALPHA_MAXIMIZED:
  9707. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9708. this._alphaState.alphaBlend = true;
  9709. break;
  9710. case Engine.ALPHA_INTERPOLATE:
  9711. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9712. this._alphaState.alphaBlend = true;
  9713. break;
  9714. case Engine.ALPHA_SCREENMODE:
  9715. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9716. this._alphaState.alphaBlend = true;
  9717. break;
  9718. }
  9719. if (!noDepthWriteChange) {
  9720. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9721. }
  9722. this._alphaMode = mode;
  9723. };
  9724. Engine.prototype.getAlphaMode = function () {
  9725. return this._alphaMode;
  9726. };
  9727. Engine.prototype.setAlphaTesting = function (enable) {
  9728. this._alphaTest = enable;
  9729. };
  9730. Engine.prototype.getAlphaTesting = function () {
  9731. return !!this._alphaTest;
  9732. };
  9733. // Textures
  9734. Engine.prototype.wipeCaches = function (bruteForce) {
  9735. if (this.preventCacheWipeBetweenFrames) {
  9736. return;
  9737. }
  9738. this.resetTextureCache();
  9739. this._currentEffect = null;
  9740. // 6/8/2017: deltakosh: Should not be required anymore.
  9741. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9742. if (bruteForce) {
  9743. this._currentProgram = null;
  9744. this._stencilState.reset();
  9745. this._depthCullingState.reset();
  9746. this.setDepthFunctionToLessOrEqual();
  9747. this._alphaState.reset();
  9748. }
  9749. this._cachedVertexBuffers = null;
  9750. this._cachedIndexBuffer = null;
  9751. this._cachedEffectForVertexBuffers = null;
  9752. this._unbindVertexArrayObject();
  9753. this.bindIndexBuffer(null);
  9754. this.bindArrayBuffer(null);
  9755. };
  9756. /**
  9757. * Set the compressed texture format to use, based on the formats you have, and the formats
  9758. * supported by the hardware / browser.
  9759. *
  9760. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9761. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9762. * to API arguments needed to compressed textures. This puts the burden on the container
  9763. * generator to house the arcane code for determining these for current & future formats.
  9764. *
  9765. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9766. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9767. *
  9768. * Note: The result of this call is not taken into account when a texture is base64.
  9769. *
  9770. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9771. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9772. *
  9773. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9774. * @returns The extension selected.
  9775. */
  9776. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9777. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9778. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9779. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9780. return this._textureFormatInUse = this._texturesSupported[i];
  9781. }
  9782. }
  9783. }
  9784. // actively set format to nothing, to allow this to be called more than once
  9785. // and possibly fail the 2nd time
  9786. return this._textureFormatInUse = null;
  9787. };
  9788. Engine.prototype._createTexture = function () {
  9789. return this._gl.createTexture();
  9790. };
  9791. /**
  9792. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9793. * @param {string} urlArg- This contains one of the following:
  9794. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9795. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9796. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9797. *
  9798. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9799. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9800. * @param {Scene} scene- Needed for loading to the correct scene.
  9801. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9802. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9803. * @param {callback} onError- Optional callback to be called upon failure.
  9804. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9805. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9806. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9807. *
  9808. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9809. */
  9810. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9811. var _this = this;
  9812. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9813. if (onLoad === void 0) { onLoad = null; }
  9814. if (onError === void 0) { onError = null; }
  9815. if (buffer === void 0) { buffer = null; }
  9816. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9817. var fromData = url.substr(0, 5) === "data:";
  9818. var fromBlob = url.substr(0, 5) === "blob:";
  9819. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9820. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9821. // establish the file extension, if possible
  9822. var lastDot = url.lastIndexOf('.');
  9823. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9824. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9825. var isTGA = (extension === ".tga");
  9826. // determine if a ktx file should be substituted
  9827. var isKTX = false;
  9828. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9829. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9830. isKTX = true;
  9831. }
  9832. if (scene) {
  9833. scene._addPendingData(texture);
  9834. }
  9835. texture.url = url;
  9836. texture.generateMipMaps = !noMipmap;
  9837. texture.samplingMode = samplingMode;
  9838. texture.invertY = invertY;
  9839. if (!this._doNotHandleContextLost) {
  9840. // Keep a link to the buffer only if we plan to handle context lost
  9841. texture._buffer = buffer;
  9842. }
  9843. if (onLoad) {
  9844. texture.onLoadedObservable.add(onLoad);
  9845. }
  9846. if (!fallBack)
  9847. this._internalTexturesCache.push(texture);
  9848. var onerror = function () {
  9849. if (scene) {
  9850. scene._removePendingData(texture);
  9851. }
  9852. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9853. if (isKTX) {
  9854. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9855. }
  9856. else if (onError) {
  9857. onError();
  9858. }
  9859. };
  9860. var callback;
  9861. // processing for non-image formats
  9862. if (isKTX || isTGA || isDDS) {
  9863. if (isKTX) {
  9864. callback = function (data) {
  9865. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9866. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9867. ktx.uploadLevels(_this._gl, !noMipmap);
  9868. return false;
  9869. }, samplingMode);
  9870. };
  9871. }
  9872. else if (isTGA) {
  9873. callback = function (arrayBuffer) {
  9874. var data = new Uint8Array(arrayBuffer);
  9875. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9876. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9877. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9878. return false;
  9879. }, samplingMode);
  9880. };
  9881. }
  9882. else if (isDDS) {
  9883. callback = function (data) {
  9884. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9885. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9886. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9887. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9888. return false;
  9889. }, samplingMode);
  9890. };
  9891. }
  9892. if (!buffer) {
  9893. BABYLON.Tools.LoadFile(url, function (data) {
  9894. callback(data);
  9895. }, null, scene ? scene.database : null, true, onerror);
  9896. }
  9897. else {
  9898. callback(buffer);
  9899. }
  9900. // image format processing
  9901. }
  9902. else {
  9903. var onload = function (img) {
  9904. if (fromBlob && !_this._doNotHandleContextLost) {
  9905. // We need to store the image if we need to rebuild the texture
  9906. // in case of a webgl context lost
  9907. texture._buffer = img;
  9908. }
  9909. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9910. var gl = _this._gl;
  9911. var isPot = (img.width === potWidth && img.height === potHeight);
  9912. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9913. if (isPot) {
  9914. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9915. return false;
  9916. }
  9917. // Using shaders to rescale because canvas.drawImage is lossy
  9918. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9919. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9920. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9921. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9922. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9923. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9924. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9925. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9926. _this._releaseTexture(source);
  9927. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9928. continuationCallback();
  9929. });
  9930. return true;
  9931. }, samplingMode);
  9932. };
  9933. if (!fromData || isBase64)
  9934. if (buffer instanceof HTMLImageElement) {
  9935. onload(buffer);
  9936. }
  9937. else {
  9938. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9939. }
  9940. else if (buffer instanceof Array || typeof buffer === "string")
  9941. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9942. else
  9943. onload(buffer);
  9944. }
  9945. return texture;
  9946. };
  9947. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9948. var _this = this;
  9949. var rtt = this.createRenderTargetTexture({
  9950. width: destination.width,
  9951. height: destination.height,
  9952. }, {
  9953. generateMipMaps: false,
  9954. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9955. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9956. generateDepthBuffer: false,
  9957. generateStencilBuffer: false
  9958. });
  9959. if (!this._rescalePostProcess) {
  9960. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9961. }
  9962. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9963. _this._rescalePostProcess.onApply = function (effect) {
  9964. effect._bindTexture("textureSampler", source);
  9965. };
  9966. var hostingScene = scene;
  9967. if (!hostingScene) {
  9968. hostingScene = _this.scenes[_this.scenes.length - 1];
  9969. }
  9970. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9971. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9972. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9973. _this.unBindFramebuffer(rtt);
  9974. _this._releaseTexture(rtt);
  9975. if (onComplete) {
  9976. onComplete();
  9977. }
  9978. });
  9979. };
  9980. Engine.prototype._getInternalFormat = function (format) {
  9981. var internalFormat = this._gl.RGBA;
  9982. switch (format) {
  9983. case Engine.TEXTUREFORMAT_ALPHA:
  9984. internalFormat = this._gl.ALPHA;
  9985. break;
  9986. case Engine.TEXTUREFORMAT_LUMINANCE:
  9987. internalFormat = this._gl.LUMINANCE;
  9988. break;
  9989. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9990. internalFormat = this._gl.LUMINANCE_ALPHA;
  9991. break;
  9992. case Engine.TEXTUREFORMAT_RGB:
  9993. internalFormat = this._gl.RGB;
  9994. break;
  9995. case Engine.TEXTUREFORMAT_RGBA:
  9996. internalFormat = this._gl.RGBA;
  9997. break;
  9998. }
  9999. return internalFormat;
  10000. };
  10001. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10002. if (compression === void 0) { compression = null; }
  10003. var internalFormat = this._getInternalFormat(format);
  10004. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10005. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10006. if (!this._doNotHandleContextLost) {
  10007. texture._bufferView = data;
  10008. texture.format = format;
  10009. texture.invertY = invertY;
  10010. texture._compression = compression;
  10011. }
  10012. if (texture.width % 4 !== 0) {
  10013. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10014. }
  10015. if (compression) {
  10016. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10017. }
  10018. else {
  10019. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10020. }
  10021. if (texture.generateMipMaps) {
  10022. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10023. }
  10024. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10025. this.resetTextureCache();
  10026. texture.isReady = true;
  10027. };
  10028. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10029. if (compression === void 0) { compression = null; }
  10030. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10031. texture.baseWidth = width;
  10032. texture.baseHeight = height;
  10033. texture.width = width;
  10034. texture.height = height;
  10035. texture.format = format;
  10036. texture.generateMipMaps = generateMipMaps;
  10037. texture.samplingMode = samplingMode;
  10038. texture.invertY = invertY;
  10039. texture._compression = compression;
  10040. if (!this._doNotHandleContextLost) {
  10041. texture._bufferView = data;
  10042. }
  10043. this.updateRawTexture(texture, data, format, invertY, compression);
  10044. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10045. // Filters
  10046. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10047. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10048. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10049. if (generateMipMaps) {
  10050. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10051. }
  10052. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10053. this._internalTexturesCache.push(texture);
  10054. return texture;
  10055. };
  10056. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10057. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10058. texture.baseWidth = width;
  10059. texture.baseHeight = height;
  10060. if (generateMipMaps) {
  10061. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10062. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10063. }
  10064. this.resetTextureCache();
  10065. texture.width = width;
  10066. texture.height = height;
  10067. texture.isReady = false;
  10068. texture.generateMipMaps = generateMipMaps;
  10069. texture.samplingMode = samplingMode;
  10070. this.updateTextureSamplingMode(samplingMode, texture);
  10071. this._internalTexturesCache.push(texture);
  10072. return texture;
  10073. };
  10074. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10075. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10076. if (texture.isCube) {
  10077. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10078. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10079. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10080. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10081. }
  10082. else {
  10083. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10084. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10085. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10086. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10087. }
  10088. texture.samplingMode = samplingMode;
  10089. };
  10090. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10091. if (premulAlpha === void 0) { premulAlpha = false; }
  10092. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10093. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10094. if (premulAlpha) {
  10095. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10096. }
  10097. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10098. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10099. if (texture.generateMipMaps) {
  10100. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10101. }
  10102. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10103. if (premulAlpha) {
  10104. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10105. }
  10106. this.resetTextureCache();
  10107. texture.isReady = true;
  10108. };
  10109. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10110. if (texture._isDisabled) {
  10111. return;
  10112. }
  10113. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10114. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10115. try {
  10116. // Testing video texture support
  10117. if (this._videoTextureSupported === undefined) {
  10118. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10119. if (this._gl.getError() !== 0) {
  10120. this._videoTextureSupported = false;
  10121. }
  10122. else {
  10123. this._videoTextureSupported = true;
  10124. }
  10125. }
  10126. // Copy video through the current working canvas if video texture is not supported
  10127. if (!this._videoTextureSupported) {
  10128. if (!texture._workingCanvas) {
  10129. texture._workingCanvas = document.createElement("canvas");
  10130. texture._workingContext = texture._workingCanvas.getContext("2d");
  10131. texture._workingCanvas.width = texture.width;
  10132. texture._workingCanvas.height = texture.height;
  10133. }
  10134. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10135. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10136. }
  10137. else {
  10138. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10139. }
  10140. if (texture.generateMipMaps) {
  10141. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10142. }
  10143. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10144. this.resetTextureCache();
  10145. texture.isReady = true;
  10146. }
  10147. catch (ex) {
  10148. // Something unexpected
  10149. // Let's disable the texture
  10150. texture._isDisabled = true;
  10151. }
  10152. };
  10153. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10154. var fullOptions = new RenderTargetCreationOptions();
  10155. if (options !== undefined && typeof options === "object") {
  10156. fullOptions.generateMipMaps = options.generateMipMaps;
  10157. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10158. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10159. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10160. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10161. }
  10162. else {
  10163. fullOptions.generateMipMaps = options;
  10164. fullOptions.generateDepthBuffer = true;
  10165. fullOptions.generateStencilBuffer = false;
  10166. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10167. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10168. }
  10169. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10170. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10171. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10172. }
  10173. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10174. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10175. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10176. }
  10177. var gl = this._gl;
  10178. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10179. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10180. var width = size.width || size;
  10181. var height = size.height || size;
  10182. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  10183. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10184. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10185. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10186. }
  10187. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10188. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10191. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10192. // Create the framebuffer
  10193. var framebuffer = gl.createFramebuffer();
  10194. this.bindUnboundFramebuffer(framebuffer);
  10195. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10196. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  10197. if (fullOptions.generateMipMaps) {
  10198. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10199. }
  10200. // Unbind
  10201. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10202. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10203. this.bindUnboundFramebuffer(null);
  10204. texture._framebuffer = framebuffer;
  10205. texture.baseWidth = width;
  10206. texture.baseHeight = height;
  10207. texture.width = width;
  10208. texture.height = height;
  10209. texture.isReady = true;
  10210. texture.samples = 1;
  10211. texture.generateMipMaps = fullOptions.generateMipMaps;
  10212. texture.samplingMode = fullOptions.samplingMode;
  10213. texture.type = fullOptions.type;
  10214. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10215. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  10216. this.resetTextureCache();
  10217. this._internalTexturesCache.push(texture);
  10218. return texture;
  10219. };
  10220. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10221. var generateMipMaps = false;
  10222. var generateDepthBuffer = true;
  10223. var generateStencilBuffer = false;
  10224. var generateDepthTexture = false;
  10225. var textureCount = 1;
  10226. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10227. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10228. var types = [], samplingModes = [];
  10229. if (options !== undefined) {
  10230. generateMipMaps = options.generateMipMaps;
  10231. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10232. generateStencilBuffer = options.generateStencilBuffer;
  10233. generateDepthTexture = options.generateDepthTexture;
  10234. textureCount = options.textureCount || 1;
  10235. if (options.types) {
  10236. types = options.types;
  10237. }
  10238. if (options.samplingModes) {
  10239. samplingModes = options.samplingModes;
  10240. }
  10241. }
  10242. var gl = this._gl;
  10243. // Create the framebuffer
  10244. var framebuffer = gl.createFramebuffer();
  10245. this.bindUnboundFramebuffer(framebuffer);
  10246. var width = size.width || size;
  10247. var height = size.height || size;
  10248. var textures = [];
  10249. var attachments = [];
  10250. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10251. for (var i = 0; i < textureCount; i++) {
  10252. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10253. var type = types[i] || defaultType;
  10254. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10255. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10256. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10257. }
  10258. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10259. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10260. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10261. }
  10262. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10263. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10264. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10265. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10266. }
  10267. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10268. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10269. textures.push(texture);
  10270. attachments.push(attachment);
  10271. gl.activeTexture(gl["TEXTURE" + i]);
  10272. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10273. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10274. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10275. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10276. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10277. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10278. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10279. if (generateMipMaps) {
  10280. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10281. }
  10282. // Unbind
  10283. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10284. texture._framebuffer = framebuffer;
  10285. texture._depthStencilBuffer = depthStencilBuffer;
  10286. texture.baseWidth = width;
  10287. texture.baseHeight = height;
  10288. texture.width = width;
  10289. texture.height = height;
  10290. texture.isReady = true;
  10291. texture.samples = 1;
  10292. texture.generateMipMaps = generateMipMaps;
  10293. texture.samplingMode = samplingMode;
  10294. texture.type = type;
  10295. texture._generateDepthBuffer = generateDepthBuffer;
  10296. texture._generateStencilBuffer = generateStencilBuffer;
  10297. this._internalTexturesCache.push(texture);
  10298. }
  10299. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10300. // Depth texture
  10301. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10302. gl.activeTexture(gl.TEXTURE0);
  10303. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10304. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10305. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10306. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10307. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10308. 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);
  10309. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10310. depthTexture._framebuffer = framebuffer;
  10311. depthTexture.baseWidth = width;
  10312. depthTexture.baseHeight = height;
  10313. depthTexture.width = width;
  10314. depthTexture.height = height;
  10315. depthTexture.isReady = true;
  10316. depthTexture.samples = 1;
  10317. depthTexture.generateMipMaps = generateMipMaps;
  10318. depthTexture.samplingMode = gl.NEAREST;
  10319. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10320. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10321. textures.push(depthTexture);
  10322. this._internalTexturesCache.push(depthTexture);
  10323. }
  10324. gl.drawBuffers(attachments);
  10325. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10326. this.bindUnboundFramebuffer(null);
  10327. this.resetTextureCache();
  10328. return textures;
  10329. };
  10330. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10331. if (samples === void 0) { samples = 1; }
  10332. var depthStencilBuffer = null;
  10333. var gl = this._gl;
  10334. // Create the depth/stencil buffer
  10335. if (generateStencilBuffer) {
  10336. depthStencilBuffer = gl.createRenderbuffer();
  10337. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10338. if (samples > 1) {
  10339. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10340. }
  10341. else {
  10342. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10343. }
  10344. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10345. }
  10346. else if (generateDepthBuffer) {
  10347. depthStencilBuffer = gl.createRenderbuffer();
  10348. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10349. if (samples > 1) {
  10350. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10351. }
  10352. else {
  10353. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10354. }
  10355. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10356. }
  10357. return depthStencilBuffer;
  10358. };
  10359. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10360. if (this.webGLVersion < 2) {
  10361. return 1;
  10362. }
  10363. if (texture.samples === samples) {
  10364. return samples;
  10365. }
  10366. var gl = this._gl;
  10367. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10368. // Dispose previous render buffers
  10369. if (texture._depthStencilBuffer) {
  10370. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10371. }
  10372. if (texture._MSAAFramebuffer) {
  10373. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10374. }
  10375. if (texture._MSAARenderBuffer) {
  10376. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10377. }
  10378. if (samples > 1) {
  10379. texture._MSAAFramebuffer = gl.createFramebuffer();
  10380. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10381. var colorRenderbuffer = gl.createRenderbuffer();
  10382. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10383. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10384. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10385. texture._MSAARenderBuffer = colorRenderbuffer;
  10386. }
  10387. else {
  10388. this.bindUnboundFramebuffer(texture._framebuffer);
  10389. }
  10390. texture.samples = samples;
  10391. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10392. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10393. this.bindUnboundFramebuffer(null);
  10394. return samples;
  10395. };
  10396. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10397. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10398. };
  10399. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10400. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10401. };
  10402. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10403. var gl = this._gl;
  10404. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10405. var generateMipMaps = true;
  10406. var generateDepthBuffer = true;
  10407. var generateStencilBuffer = false;
  10408. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10409. if (options !== undefined) {
  10410. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10411. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10412. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10413. if (options.samplingMode !== undefined) {
  10414. samplingMode = options.samplingMode;
  10415. }
  10416. }
  10417. texture.isCube = true;
  10418. texture.generateMipMaps = generateMipMaps;
  10419. texture.samples = 1;
  10420. texture.samplingMode = samplingMode;
  10421. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10422. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10423. for (var face = 0; face < 6; face++) {
  10424. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10425. }
  10426. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10427. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10428. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10429. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10430. // Create the framebuffer
  10431. var framebuffer = gl.createFramebuffer();
  10432. this.bindUnboundFramebuffer(framebuffer);
  10433. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10434. // Mipmaps
  10435. if (texture.generateMipMaps) {
  10436. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10437. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10438. }
  10439. // Unbind
  10440. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10441. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10442. this.bindUnboundFramebuffer(null);
  10443. texture._framebuffer = framebuffer;
  10444. texture.width = size;
  10445. texture.height = size;
  10446. texture.isReady = true;
  10447. this.resetTextureCache();
  10448. this._internalTexturesCache.push(texture);
  10449. return texture;
  10450. };
  10451. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10452. var _this = this;
  10453. if (onError === void 0) { onError = null; }
  10454. if (forcedExtension === void 0) { forcedExtension = null; }
  10455. var callback = function (loadData) {
  10456. if (!loadData) {
  10457. if (onLoad) {
  10458. onLoad(null);
  10459. }
  10460. return;
  10461. }
  10462. var texture = loadData.texture;
  10463. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10464. texture._lodGenerationScale = scale;
  10465. texture._lodGenerationOffset = offset;
  10466. if (_this._caps.textureLOD) {
  10467. // Do not add extra process if texture lod is supported.
  10468. if (onLoad) {
  10469. onLoad(texture);
  10470. }
  10471. return;
  10472. }
  10473. var mipSlices = 3;
  10474. var gl = _this._gl;
  10475. var width = loadData.width;
  10476. if (!width) {
  10477. return;
  10478. }
  10479. var textures = [];
  10480. for (var i = 0; i < mipSlices; i++) {
  10481. //compute LOD from even spacing in smoothness (matching shader calculation)
  10482. var smoothness = i / (mipSlices - 1);
  10483. var roughness = 1 - smoothness;
  10484. var minLODIndex = offset; // roughness = 0
  10485. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10486. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10487. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10488. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10489. glTextureFromLod.isCube = true;
  10490. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10491. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10492. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10493. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10494. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10495. if (loadData.isDDS) {
  10496. var info = loadData.info;
  10497. var data = loadData.data;
  10498. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10499. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10500. }
  10501. else {
  10502. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10503. }
  10504. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10505. // Wrap in a base texture for easy binding.
  10506. var lodTexture = new BABYLON.BaseTexture(scene);
  10507. lodTexture.isCube = true;
  10508. lodTexture._texture = glTextureFromLod;
  10509. glTextureFromLod.isReady = true;
  10510. textures.push(lodTexture);
  10511. }
  10512. texture._lodTextureHigh = textures[2];
  10513. texture._lodTextureMid = textures[1];
  10514. texture._lodTextureLow = textures[0];
  10515. if (onLoad) {
  10516. onLoad(texture);
  10517. }
  10518. };
  10519. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10520. };
  10521. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10522. var _this = this;
  10523. if (onLoad === void 0) { onLoad = null; }
  10524. if (onError === void 0) { onError = null; }
  10525. if (forcedExtension === void 0) { forcedExtension = null; }
  10526. var gl = this._gl;
  10527. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10528. texture.isCube = true;
  10529. texture.url = rootUrl;
  10530. texture.generateMipMaps = !noMipmap;
  10531. if (!this._doNotHandleContextLost) {
  10532. texture._extension = forcedExtension;
  10533. texture._files = files;
  10534. }
  10535. var isKTX = false;
  10536. var isDDS = false;
  10537. var lastDot = rootUrl.lastIndexOf('.');
  10538. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10539. if (this._textureFormatInUse) {
  10540. extension = this._textureFormatInUse;
  10541. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10542. isKTX = true;
  10543. }
  10544. else {
  10545. isDDS = (extension === ".dds");
  10546. }
  10547. var onerror = function (request, exception) {
  10548. if (onError) {
  10549. onError(request.status + " " + request.statusText, exception);
  10550. }
  10551. };
  10552. if (isKTX) {
  10553. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10554. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10555. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10556. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10557. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10558. ktx.uploadLevels(_this._gl, !noMipmap);
  10559. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10560. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10561. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10562. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10563. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10564. _this.resetTextureCache();
  10565. texture.width = ktx.pixelWidth;
  10566. texture.height = ktx.pixelHeight;
  10567. texture.isReady = true;
  10568. }, null, null, true, onerror);
  10569. }
  10570. else if (isDDS) {
  10571. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10572. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10573. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10574. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10575. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10576. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10577. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10578. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10579. }
  10580. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10581. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10582. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10583. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10584. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10585. _this.resetTextureCache();
  10586. texture.width = info.width;
  10587. texture.height = info.height;
  10588. texture.isReady = true;
  10589. texture.type = info.textureType;
  10590. if (onLoad) {
  10591. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10592. }
  10593. }, null, null, true, onerror);
  10594. }
  10595. else {
  10596. cascadeLoad(rootUrl, scene, function (imgs) {
  10597. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10598. var height = width;
  10599. _this._prepareWorkingCanvas();
  10600. _this._workingCanvas.width = width;
  10601. _this._workingCanvas.height = height;
  10602. var faces = [
  10603. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10604. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10605. ];
  10606. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10607. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10608. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10609. for (var index = 0; index < faces.length; index++) {
  10610. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10611. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10612. }
  10613. if (!noMipmap) {
  10614. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10615. }
  10616. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10617. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10618. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10619. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10620. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10621. _this.resetTextureCache();
  10622. texture.width = width;
  10623. texture.height = height;
  10624. texture.isReady = true;
  10625. texture.format = format;
  10626. texture.onLoadedObservable.notifyObservers(texture);
  10627. texture.onLoadedObservable.clear();
  10628. if (onLoad) {
  10629. onLoad();
  10630. }
  10631. }, files, onError);
  10632. }
  10633. this._internalTexturesCache.push(texture);
  10634. return texture;
  10635. };
  10636. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10637. if (compression === void 0) { compression = null; }
  10638. if (level === void 0) { level = 0; }
  10639. texture._bufferViewArray = data;
  10640. texture.format = format;
  10641. texture.type = type;
  10642. texture.invertY = invertY;
  10643. texture._compression = compression;
  10644. var gl = this._gl;
  10645. var textureType = this._getWebGLTextureType(type);
  10646. var internalFormat = this._getInternalFormat(format);
  10647. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10648. var needConversion = false;
  10649. if (internalFormat === gl.RGB) {
  10650. internalFormat = gl.RGBA;
  10651. needConversion = true;
  10652. }
  10653. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10654. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10655. if (texture.width % 4 !== 0) {
  10656. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10657. }
  10658. // Data are known to be in +X +Y +Z -X -Y -Z
  10659. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10660. var faceData = data[faceIndex];
  10661. if (compression) {
  10662. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10663. }
  10664. else {
  10665. if (needConversion) {
  10666. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10667. }
  10668. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10669. }
  10670. }
  10671. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10672. if (isPot && texture.generateMipMaps && level === 0) {
  10673. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10674. }
  10675. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10676. this.resetTextureCache();
  10677. texture.isReady = true;
  10678. };
  10679. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10680. if (compression === void 0) { compression = null; }
  10681. var gl = this._gl;
  10682. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10683. texture.isCube = true;
  10684. texture.generateMipMaps = generateMipMaps;
  10685. texture.format = format;
  10686. texture.type = type;
  10687. if (!this._doNotHandleContextLost) {
  10688. texture._bufferViewArray = data;
  10689. }
  10690. var textureType = this._getWebGLTextureType(type);
  10691. var internalFormat = this._getInternalFormat(format);
  10692. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10693. var needConversion = false;
  10694. if (internalFormat === gl.RGB) {
  10695. internalFormat = gl.RGBA;
  10696. needConversion = true;
  10697. }
  10698. var width = size;
  10699. var height = width;
  10700. texture.width = width;
  10701. texture.height = height;
  10702. // Double check on POT to generate Mips.
  10703. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10704. if (!isPot) {
  10705. generateMipMaps = false;
  10706. }
  10707. // Upload data if needed. The texture won't be ready until then.
  10708. if (data) {
  10709. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10710. }
  10711. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10712. // Filters
  10713. if (data && generateMipMaps) {
  10714. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10715. }
  10716. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10717. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10719. }
  10720. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10721. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10722. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10723. }
  10724. else {
  10725. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10726. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10728. }
  10729. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10731. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10732. return texture;
  10733. };
  10734. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10735. var _this = this;
  10736. if (onLoad === void 0) { onLoad = null; }
  10737. if (onError === void 0) { onError = null; }
  10738. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10739. if (invertY === void 0) { invertY = false; }
  10740. var gl = this._gl;
  10741. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10742. scene._addPendingData(texture);
  10743. texture.url = url;
  10744. this._internalTexturesCache.push(texture);
  10745. var onerror = function (request, exception) {
  10746. scene._removePendingData(texture);
  10747. if (onError) {
  10748. onError(request.status + " " + request.statusText, exception);
  10749. }
  10750. };
  10751. var internalCallback = function (data) {
  10752. var width = texture.width;
  10753. var height = texture.height;
  10754. var faceDataArrays = callback(data);
  10755. if (mipmmapGenerator) {
  10756. var textureType = _this._getWebGLTextureType(type);
  10757. var internalFormat = _this._getInternalFormat(format);
  10758. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10759. var needConversion = false;
  10760. if (internalFormat === gl.RGB) {
  10761. internalFormat = gl.RGBA;
  10762. needConversion = true;
  10763. }
  10764. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10765. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10766. var mipData = mipmmapGenerator(faceDataArrays);
  10767. for (var level = 0; level < mipData.length; level++) {
  10768. var mipSize = width >> level;
  10769. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10770. var mipFaceData = mipData[level][faceIndex];
  10771. if (needConversion) {
  10772. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10773. }
  10774. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10775. }
  10776. }
  10777. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10778. }
  10779. else {
  10780. texture.generateMipMaps = !noMipmap;
  10781. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10782. }
  10783. texture.isReady = true;
  10784. _this.resetTextureCache();
  10785. scene._removePendingData(texture);
  10786. if (onLoad) {
  10787. onLoad();
  10788. }
  10789. };
  10790. BABYLON.Tools.LoadFile(url, function (data) {
  10791. internalCallback(data);
  10792. }, undefined, scene.database, true, onerror);
  10793. return texture;
  10794. };
  10795. ;
  10796. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10797. var gl = this._gl;
  10798. if (!gl) {
  10799. return;
  10800. }
  10801. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10802. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10803. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10804. if (!noMipmap && !isCompressed) {
  10805. gl.generateMipmap(gl.TEXTURE_2D);
  10806. }
  10807. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10808. this.resetTextureCache();
  10809. if (scene) {
  10810. scene._removePendingData(texture);
  10811. }
  10812. texture.onLoadedObservable.notifyObservers(texture);
  10813. texture.onLoadedObservable.clear();
  10814. };
  10815. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10816. var _this = this;
  10817. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10818. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10819. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10820. var gl = this._gl;
  10821. if (!gl) {
  10822. return;
  10823. }
  10824. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10825. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10826. texture.baseWidth = width;
  10827. texture.baseHeight = height;
  10828. texture.width = potWidth;
  10829. texture.height = potHeight;
  10830. texture.isReady = true;
  10831. if (processFunction(potWidth, potHeight, function () {
  10832. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10833. })) {
  10834. // Returning as texture needs extra async steps
  10835. return;
  10836. }
  10837. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10838. };
  10839. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10840. // Create new RGBA data container.
  10841. var rgbaData;
  10842. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10843. rgbaData = new Float32Array(width * height * 4);
  10844. }
  10845. else {
  10846. rgbaData = new Uint32Array(width * height * 4);
  10847. }
  10848. // Convert each pixel.
  10849. for (var x = 0; x < width; x++) {
  10850. for (var y = 0; y < height; y++) {
  10851. var index = (y * width + x) * 3;
  10852. var newIndex = (y * width + x) * 4;
  10853. // Map Old Value to new value.
  10854. rgbaData[newIndex + 0] = rgbData[index + 0];
  10855. rgbaData[newIndex + 1] = rgbData[index + 1];
  10856. rgbaData[newIndex + 2] = rgbData[index + 2];
  10857. // Add fully opaque alpha channel.
  10858. rgbaData[newIndex + 3] = 1;
  10859. }
  10860. }
  10861. return rgbaData;
  10862. };
  10863. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10864. var gl = this._gl;
  10865. if (texture._framebuffer) {
  10866. gl.deleteFramebuffer(texture._framebuffer);
  10867. texture._framebuffer = null;
  10868. }
  10869. if (texture._depthStencilBuffer) {
  10870. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10871. texture._depthStencilBuffer = null;
  10872. }
  10873. if (texture._MSAAFramebuffer) {
  10874. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10875. texture._MSAAFramebuffer = null;
  10876. }
  10877. if (texture._MSAARenderBuffer) {
  10878. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10879. texture._MSAARenderBuffer = null;
  10880. }
  10881. };
  10882. Engine.prototype._releaseTexture = function (texture) {
  10883. var gl = this._gl;
  10884. this._releaseFramebufferObjects(texture);
  10885. gl.deleteTexture(texture._webGLTexture);
  10886. // Unbind channels
  10887. this.unbindAllTextures();
  10888. var index = this._internalTexturesCache.indexOf(texture);
  10889. if (index !== -1) {
  10890. this._internalTexturesCache.splice(index, 1);
  10891. }
  10892. // Integrated fixed lod samplers.
  10893. if (texture._lodTextureHigh) {
  10894. texture._lodTextureHigh.dispose();
  10895. }
  10896. if (texture._lodTextureMid) {
  10897. texture._lodTextureMid.dispose();
  10898. }
  10899. if (texture._lodTextureLow) {
  10900. texture._lodTextureLow.dispose();
  10901. }
  10902. };
  10903. Engine.prototype.setProgram = function (program) {
  10904. if (this._currentProgram !== program) {
  10905. this._gl.useProgram(program);
  10906. this._currentProgram = program;
  10907. }
  10908. };
  10909. Engine.prototype.bindSamplers = function (effect) {
  10910. this.setProgram(effect.getProgram());
  10911. var samplers = effect.getSamplers();
  10912. for (var index = 0; index < samplers.length; index++) {
  10913. var uniform = effect.getUniform(samplers[index]);
  10914. this._gl.uniform1i(uniform, index);
  10915. }
  10916. this._currentEffect = null;
  10917. };
  10918. Engine.prototype.activateTexture = function (texture) {
  10919. if (this._activeTexture !== texture) {
  10920. this._gl.activeTexture(texture);
  10921. this._activeTexture = texture;
  10922. }
  10923. };
  10924. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10925. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10926. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10927. this._activeTexturesCache[this._activeTexture] = texture;
  10928. }
  10929. };
  10930. Engine.prototype._bindTexture = function (channel, texture) {
  10931. if (channel < 0) {
  10932. return;
  10933. }
  10934. this.activateTexture(this._gl.TEXTURE0 + channel);
  10935. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10936. };
  10937. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10938. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10939. };
  10940. Engine.prototype.unbindAllTextures = function () {
  10941. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10942. this.activateTexture(this._gl["TEXTURE" + channel]);
  10943. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10944. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10945. }
  10946. };
  10947. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10948. if (channel < 0) {
  10949. return;
  10950. }
  10951. this._gl.uniform1i(uniform, channel);
  10952. this._setTexture(channel, texture);
  10953. };
  10954. Engine.prototype._setTexture = function (channel, texture) {
  10955. // Not ready?
  10956. if (!texture) {
  10957. if (this._activeTexturesCache[channel] != null) {
  10958. this.activateTexture(this._gl["TEXTURE" + channel]);
  10959. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10960. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10961. }
  10962. return;
  10963. }
  10964. // Video
  10965. var alreadyActivated = false;
  10966. if (texture.video) {
  10967. this.activateTexture(this._gl["TEXTURE" + channel]);
  10968. alreadyActivated = true;
  10969. texture.update();
  10970. }
  10971. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10972. texture.delayLoad();
  10973. return;
  10974. }
  10975. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10976. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10977. if (this._activeTexturesCache[channel] === internalTexture) {
  10978. return;
  10979. }
  10980. if (!alreadyActivated) {
  10981. this.activateTexture(this._gl["TEXTURE" + channel]);
  10982. }
  10983. if (internalTexture.isCube) {
  10984. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10985. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10986. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10987. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10988. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10989. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10990. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10991. }
  10992. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10993. }
  10994. else {
  10995. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10996. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10997. internalTexture._cachedWrapU = texture.wrapU;
  10998. switch (texture.wrapU) {
  10999. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11000. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11001. break;
  11002. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11003. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11004. break;
  11005. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11006. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11007. break;
  11008. }
  11009. }
  11010. if (internalTexture._cachedWrapV !== texture.wrapV) {
  11011. internalTexture._cachedWrapV = texture.wrapV;
  11012. switch (texture.wrapV) {
  11013. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11014. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11015. break;
  11016. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11017. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11018. break;
  11019. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11020. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11021. break;
  11022. }
  11023. }
  11024. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11025. }
  11026. };
  11027. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11028. if (channel < 0) {
  11029. return;
  11030. }
  11031. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11032. this._textureUnits = new Int32Array(textures.length);
  11033. }
  11034. for (var i = 0; i < textures.length; i++) {
  11035. this._textureUnits[i] = channel + i;
  11036. }
  11037. this._gl.uniform1iv(uniform, this._textureUnits);
  11038. for (var index = 0; index < textures.length; index++) {
  11039. this._setTexture(channel + index, textures[index]);
  11040. }
  11041. };
  11042. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11043. var internalTexture = texture.getInternalTexture();
  11044. if (!internalTexture) {
  11045. return;
  11046. }
  11047. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11048. var value = texture.anisotropicFilteringLevel;
  11049. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11050. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11051. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11052. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11053. }
  11054. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11055. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11056. internalTexture._cachedAnisotropicFilteringLevel = value;
  11057. }
  11058. };
  11059. Engine.prototype.readPixels = function (x, y, width, height) {
  11060. var data = new Uint8Array(height * width * 4);
  11061. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11062. return data;
  11063. };
  11064. /**
  11065. * Add an externaly attached data from its key.
  11066. * This method call will fail and return false, if such key already exists.
  11067. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11068. * @param key the unique key that identifies the data
  11069. * @param data the data object to associate to the key for this Engine instance
  11070. * @return true if no such key were already present and the data was added successfully, false otherwise
  11071. */
  11072. Engine.prototype.addExternalData = function (key, data) {
  11073. if (!this._externalData) {
  11074. this._externalData = new BABYLON.StringDictionary();
  11075. }
  11076. return this._externalData.add(key, data);
  11077. };
  11078. /**
  11079. * Get an externaly attached data from its key
  11080. * @param key the unique key that identifies the data
  11081. * @return the associated data, if present (can be null), or undefined if not present
  11082. */
  11083. Engine.prototype.getExternalData = function (key) {
  11084. if (!this._externalData) {
  11085. this._externalData = new BABYLON.StringDictionary();
  11086. }
  11087. return this._externalData.get(key);
  11088. };
  11089. /**
  11090. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11091. * @param key the unique key that identifies the data
  11092. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11093. * @return the associated data, can be null if the factory returned null.
  11094. */
  11095. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11096. if (!this._externalData) {
  11097. this._externalData = new BABYLON.StringDictionary();
  11098. }
  11099. return this._externalData.getOrAddWithFactory(key, factory);
  11100. };
  11101. /**
  11102. * Remove an externaly attached data from the Engine instance
  11103. * @param key the unique key that identifies the data
  11104. * @return true if the data was successfully removed, false if it doesn't exist
  11105. */
  11106. Engine.prototype.removeExternalData = function (key) {
  11107. if (!this._externalData) {
  11108. this._externalData = new BABYLON.StringDictionary();
  11109. }
  11110. return this._externalData.remove(key);
  11111. };
  11112. Engine.prototype.unbindAllAttributes = function () {
  11113. if (this._mustWipeVertexAttributes) {
  11114. this._mustWipeVertexAttributes = false;
  11115. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11116. this._gl.disableVertexAttribArray(i);
  11117. this._vertexAttribArraysEnabled[i] = false;
  11118. this._currentBufferPointers[i].active = false;
  11119. }
  11120. return;
  11121. }
  11122. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11123. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11124. continue;
  11125. }
  11126. this._gl.disableVertexAttribArray(i);
  11127. this._vertexAttribArraysEnabled[i] = false;
  11128. this._currentBufferPointers[i].active = false;
  11129. }
  11130. };
  11131. Engine.prototype.releaseEffects = function () {
  11132. for (var name in this._compiledEffects) {
  11133. this._gl.deleteProgram(this._compiledEffects[name]._program);
  11134. }
  11135. this._compiledEffects = {};
  11136. };
  11137. // Dispose
  11138. Engine.prototype.dispose = function () {
  11139. this.hideLoadingUI();
  11140. this.stopRenderLoop();
  11141. // Release postProcesses
  11142. while (this.postProcesses.length) {
  11143. this.postProcesses[0].dispose();
  11144. }
  11145. // Empty texture
  11146. if (this._emptyTexture) {
  11147. this._releaseTexture(this._emptyTexture);
  11148. this._emptyTexture = null;
  11149. }
  11150. if (this._emptyCubeTexture) {
  11151. this._releaseTexture(this._emptyCubeTexture);
  11152. this._emptyCubeTexture = null;
  11153. }
  11154. // Rescale PP
  11155. if (this._rescalePostProcess) {
  11156. this._rescalePostProcess.dispose();
  11157. }
  11158. // Release scenes
  11159. while (this.scenes.length) {
  11160. this.scenes[0].dispose();
  11161. }
  11162. // Release audio engine
  11163. if (Engine.audioEngine) {
  11164. Engine.audioEngine.dispose();
  11165. }
  11166. // Release effects
  11167. this.releaseEffects();
  11168. // Unbind
  11169. this.unbindAllAttributes();
  11170. if (this._dummyFramebuffer) {
  11171. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11172. }
  11173. this._gl = null;
  11174. //WebVR
  11175. this.disableVR();
  11176. // Events
  11177. window.removeEventListener("blur", this._onBlur);
  11178. window.removeEventListener("focus", this._onFocus);
  11179. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11180. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11181. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11182. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11183. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11184. if (!this._doNotHandleContextLost) {
  11185. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11186. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11187. }
  11188. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11189. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11190. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11191. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11192. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11193. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11194. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11195. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11196. if (this._onVrDisplayConnect) {
  11197. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11198. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11199. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11200. this._onVrDisplayConnect = undefined;
  11201. this._onVrDisplayDisconnect = undefined;
  11202. }
  11203. // Remove from Instances
  11204. var index = Engine.Instances.indexOf(this);
  11205. if (index >= 0) {
  11206. Engine.Instances.splice(index, 1);
  11207. }
  11208. this._workingCanvas = null;
  11209. this._workingContext = null;
  11210. this._currentBufferPointers = null;
  11211. this._renderingCanvas = null;
  11212. this._currentProgram = null;
  11213. this.onResizeObservable.clear();
  11214. this.onCanvasBlurObservable.clear();
  11215. this.onCanvasFocusObservable.clear();
  11216. this.onCanvasPointerOutObservable.clear();
  11217. BABYLON.Effect.ResetCache();
  11218. };
  11219. // Loading screen
  11220. Engine.prototype.displayLoadingUI = function () {
  11221. var loadingScreen = this.loadingScreen;
  11222. if (loadingScreen) {
  11223. loadingScreen.displayLoadingUI();
  11224. }
  11225. };
  11226. Engine.prototype.hideLoadingUI = function () {
  11227. var loadingScreen = this.loadingScreen;
  11228. if (loadingScreen) {
  11229. loadingScreen.hideLoadingUI();
  11230. }
  11231. };
  11232. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11233. get: function () {
  11234. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  11235. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11236. return this._loadingScreen;
  11237. },
  11238. set: function (loadingScreen) {
  11239. this._loadingScreen = loadingScreen;
  11240. },
  11241. enumerable: true,
  11242. configurable: true
  11243. });
  11244. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11245. set: function (text) {
  11246. this.loadingScreen.loadingUIText = text;
  11247. },
  11248. enumerable: true,
  11249. configurable: true
  11250. });
  11251. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11252. set: function (color) {
  11253. this.loadingScreen.loadingUIBackgroundColor = color;
  11254. },
  11255. enumerable: true,
  11256. configurable: true
  11257. });
  11258. Engine.prototype.attachContextLostEvent = function (callback) {
  11259. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11260. };
  11261. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11262. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11263. };
  11264. Engine.prototype.getVertexShaderSource = function (program) {
  11265. var shaders = this._gl.getAttachedShaders(program);
  11266. return this._gl.getShaderSource(shaders[0]);
  11267. };
  11268. Engine.prototype.getFragmentShaderSource = function (program) {
  11269. var shaders = this._gl.getAttachedShaders(program);
  11270. return this._gl.getShaderSource(shaders[1]);
  11271. };
  11272. Engine.prototype.getError = function () {
  11273. return this._gl.getError();
  11274. };
  11275. // FPS
  11276. Engine.prototype.getFps = function () {
  11277. return this._fps;
  11278. };
  11279. Engine.prototype.getDeltaTime = function () {
  11280. return this._deltaTime;
  11281. };
  11282. Engine.prototype._measureFps = function () {
  11283. this._performanceMonitor.sampleFrame();
  11284. this._fps = this._performanceMonitor.averageFPS;
  11285. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11286. };
  11287. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11288. if (faceIndex === void 0) { faceIndex = -1; }
  11289. var gl = this._gl;
  11290. if (!this._dummyFramebuffer) {
  11291. this._dummyFramebuffer = gl.createFramebuffer();
  11292. }
  11293. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11294. if (faceIndex > -1) {
  11295. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11296. }
  11297. else {
  11298. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11299. }
  11300. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11301. var buffer;
  11302. switch (readType) {
  11303. case gl.UNSIGNED_BYTE:
  11304. buffer = new Uint8Array(4 * width * height);
  11305. readType = gl.UNSIGNED_BYTE;
  11306. break;
  11307. default:
  11308. buffer = new Float32Array(4 * width * height);
  11309. readType = gl.FLOAT;
  11310. break;
  11311. }
  11312. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11313. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11314. return buffer;
  11315. };
  11316. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11317. if (this._webGLVersion > 1) {
  11318. return this._caps.colorBufferFloat;
  11319. }
  11320. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11321. };
  11322. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11323. if (this._webGLVersion > 1) {
  11324. return this._caps.colorBufferFloat;
  11325. }
  11326. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11327. };
  11328. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11329. Engine.prototype._canRenderToFramebuffer = function (type) {
  11330. var gl = this._gl;
  11331. //clear existing errors
  11332. while (gl.getError() !== gl.NO_ERROR) { }
  11333. var successful = true;
  11334. var texture = gl.createTexture();
  11335. gl.bindTexture(gl.TEXTURE_2D, texture);
  11336. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11337. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11338. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11339. var fb = gl.createFramebuffer();
  11340. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11341. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11342. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11343. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11344. successful = successful && (gl.getError() === gl.NO_ERROR);
  11345. //try render by clearing frame buffer's color buffer
  11346. if (successful) {
  11347. gl.clear(gl.COLOR_BUFFER_BIT);
  11348. successful = successful && (gl.getError() === gl.NO_ERROR);
  11349. }
  11350. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11351. if (successful) {
  11352. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11353. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11354. var readFormat = gl.RGBA;
  11355. var readType = gl.UNSIGNED_BYTE;
  11356. var buffer = new Uint8Array(4);
  11357. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11358. successful = successful && (gl.getError() === gl.NO_ERROR);
  11359. }
  11360. //clean up
  11361. gl.deleteTexture(texture);
  11362. gl.deleteFramebuffer(fb);
  11363. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11364. //clear accumulated errors
  11365. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11366. return successful;
  11367. };
  11368. Engine.prototype._getWebGLTextureType = function (type) {
  11369. if (type === Engine.TEXTURETYPE_FLOAT) {
  11370. return this._gl.FLOAT;
  11371. }
  11372. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11373. // Add Half Float Constant.
  11374. return this._gl.HALF_FLOAT_OES;
  11375. }
  11376. return this._gl.UNSIGNED_BYTE;
  11377. };
  11378. ;
  11379. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11380. if (this._webGLVersion === 1) {
  11381. return this._gl.RGBA;
  11382. }
  11383. if (type === Engine.TEXTURETYPE_FLOAT) {
  11384. return this._gl.RGBA32F;
  11385. }
  11386. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11387. return this._gl.RGBA16F;
  11388. }
  11389. return this._gl.RGBA;
  11390. };
  11391. ;
  11392. Engine.prototype.createQuery = function () {
  11393. return this._gl.createQuery();
  11394. };
  11395. Engine.prototype.deleteQuery = function (query) {
  11396. this._gl.deleteQuery(query);
  11397. return this;
  11398. };
  11399. Engine.prototype.isQueryResultAvailable = function (query) {
  11400. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11401. };
  11402. Engine.prototype.getQueryResult = function (query) {
  11403. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11404. };
  11405. Engine.prototype.beginQuery = function (algorithmType, query) {
  11406. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11407. this._gl.beginQuery(glAlgorithm, query);
  11408. };
  11409. Engine.prototype.endQuery = function (algorithmType) {
  11410. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11411. this._gl.endQuery(glAlgorithm);
  11412. return this;
  11413. };
  11414. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11415. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11416. };
  11417. // Statics
  11418. Engine.isSupported = function () {
  11419. try {
  11420. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11421. if (navigator.isCocoonJS) {
  11422. return true;
  11423. }
  11424. var tempcanvas = document.createElement("canvas");
  11425. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11426. return gl != null && !!window.WebGLRenderingContext;
  11427. }
  11428. catch (e) {
  11429. return false;
  11430. }
  11431. };
  11432. return Engine;
  11433. }());
  11434. Engine.Instances = new Array();
  11435. // Const statics
  11436. Engine._ALPHA_DISABLE = 0;
  11437. Engine._ALPHA_ADD = 1;
  11438. Engine._ALPHA_COMBINE = 2;
  11439. Engine._ALPHA_SUBTRACT = 3;
  11440. Engine._ALPHA_MULTIPLY = 4;
  11441. Engine._ALPHA_MAXIMIZED = 5;
  11442. Engine._ALPHA_ONEONE = 6;
  11443. Engine._ALPHA_PREMULTIPLIED = 7;
  11444. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11445. Engine._ALPHA_INTERPOLATE = 9;
  11446. Engine._ALPHA_SCREENMODE = 10;
  11447. Engine._DELAYLOADSTATE_NONE = 0;
  11448. Engine._DELAYLOADSTATE_LOADED = 1;
  11449. Engine._DELAYLOADSTATE_LOADING = 2;
  11450. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11451. Engine._TEXTUREFORMAT_ALPHA = 0;
  11452. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11453. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11454. Engine._TEXTUREFORMAT_RGB = 4;
  11455. Engine._TEXTUREFORMAT_RGBA = 5;
  11456. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11457. Engine._TEXTURETYPE_FLOAT = 1;
  11458. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11459. // Depht or Stencil test Constants.
  11460. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11461. 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.
  11462. 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.
  11463. 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.
  11464. 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.
  11465. 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.
  11466. 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.
  11467. 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.
  11468. // Stencil Actions Constants.
  11469. Engine._KEEP = 0x1E00;
  11470. Engine._REPLACE = 0x1E01;
  11471. Engine._INCR = 0x1E02;
  11472. Engine._DECR = 0x1E03;
  11473. Engine._INVERT = 0x150A;
  11474. Engine._INCR_WRAP = 0x8507;
  11475. Engine._DECR_WRAP = 0x8508;
  11476. // Texture rescaling mode
  11477. Engine._SCALEMODE_FLOOR = 1;
  11478. Engine._SCALEMODE_NEAREST = 2;
  11479. Engine._SCALEMODE_CEILING = 3;
  11480. // Updatable statics so stick with vars here
  11481. Engine.CollisionsEpsilon = 0.001;
  11482. Engine.CodeRepository = "src/";
  11483. Engine.ShadersRepository = "src/Shaders/";
  11484. BABYLON.Engine = Engine;
  11485. })(BABYLON || (BABYLON = {}));
  11486. //# sourceMappingURL=babylon.engine.js.map
  11487. /// <reference path="Tools\babylon.decorators.ts" />
  11488. var BABYLON;
  11489. (function (BABYLON) {
  11490. /**
  11491. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11492. */
  11493. var Node = (function () {
  11494. /**
  11495. * @constructor
  11496. * @param {string} name - the name and id to be given to this node
  11497. * @param {BABYLON.Scene} the scene this node will be added to
  11498. */
  11499. function Node(name, scene) {
  11500. this.state = "";
  11501. this.metadata = null;
  11502. this.doNotSerialize = false;
  11503. this.animations = new Array();
  11504. this._ranges = {};
  11505. this._childrenFlag = -1;
  11506. this._isEnabled = true;
  11507. this._isReady = true;
  11508. this._currentRenderId = -1;
  11509. this._parentRenderId = -1;
  11510. /**
  11511. * An event triggered when the mesh is disposed.
  11512. * @type {BABYLON.Observable}
  11513. */
  11514. this.onDisposeObservable = new BABYLON.Observable();
  11515. // Behaviors
  11516. this._behaviors = new Array();
  11517. this.name = name;
  11518. this.id = name;
  11519. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11520. this._initCache();
  11521. }
  11522. Object.defineProperty(Node.prototype, "parent", {
  11523. get: function () {
  11524. return this._parentNode;
  11525. },
  11526. set: function (parent) {
  11527. if (this._parentNode === parent) {
  11528. return;
  11529. }
  11530. if (this._parentNode) {
  11531. var index = this._parentNode._children.indexOf(this);
  11532. if (index !== -1) {
  11533. this._parentNode._children.splice(index, 1);
  11534. }
  11535. }
  11536. this._parentNode = parent;
  11537. if (this._parentNode) {
  11538. if (!this._parentNode._children) {
  11539. this._parentNode._children = new Array();
  11540. }
  11541. this._parentNode._children.push(this);
  11542. }
  11543. },
  11544. enumerable: true,
  11545. configurable: true
  11546. });
  11547. Node.prototype.getClassName = function () {
  11548. return "Node";
  11549. };
  11550. Object.defineProperty(Node.prototype, "onDispose", {
  11551. set: function (callback) {
  11552. if (this._onDisposeObserver) {
  11553. this.onDisposeObservable.remove(this._onDisposeObserver);
  11554. }
  11555. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11556. },
  11557. enumerable: true,
  11558. configurable: true
  11559. });
  11560. Node.prototype.getScene = function () {
  11561. return this._scene;
  11562. };
  11563. Node.prototype.getEngine = function () {
  11564. return this._scene.getEngine();
  11565. };
  11566. Node.prototype.addBehavior = function (behavior) {
  11567. var index = this._behaviors.indexOf(behavior);
  11568. if (index !== -1) {
  11569. return;
  11570. }
  11571. behavior.attach(this);
  11572. this._behaviors.push(behavior);
  11573. return this;
  11574. };
  11575. Node.prototype.removeBehavior = function (behavior) {
  11576. var index = this._behaviors.indexOf(behavior);
  11577. if (index === -1) {
  11578. return;
  11579. }
  11580. this._behaviors[index].detach();
  11581. this._behaviors.splice(index, 1);
  11582. return this;
  11583. };
  11584. Object.defineProperty(Node.prototype, "behaviors", {
  11585. get: function () {
  11586. return this._behaviors;
  11587. },
  11588. enumerable: true,
  11589. configurable: true
  11590. });
  11591. Node.prototype.getBehaviorByName = function (name) {
  11592. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11593. var behavior = _a[_i];
  11594. if (behavior.name === name) {
  11595. return behavior;
  11596. }
  11597. }
  11598. return null;
  11599. };
  11600. // override it in derived class
  11601. Node.prototype.getWorldMatrix = function () {
  11602. return BABYLON.Matrix.Identity();
  11603. };
  11604. // override it in derived class if you add new variables to the cache
  11605. // and call the parent class method
  11606. Node.prototype._initCache = function () {
  11607. this._cache = {};
  11608. this._cache.parent = undefined;
  11609. };
  11610. Node.prototype.updateCache = function (force) {
  11611. if (!force && this.isSynchronized())
  11612. return;
  11613. this._cache.parent = this.parent;
  11614. this._updateCache();
  11615. };
  11616. // override it in derived class if you add new variables to the cache
  11617. // and call the parent class method if !ignoreParentClass
  11618. Node.prototype._updateCache = function (ignoreParentClass) {
  11619. };
  11620. // override it in derived class if you add new variables to the cache
  11621. Node.prototype._isSynchronized = function () {
  11622. return true;
  11623. };
  11624. Node.prototype._markSyncedWithParent = function () {
  11625. this._parentRenderId = this.parent._currentRenderId;
  11626. };
  11627. Node.prototype.isSynchronizedWithParent = function () {
  11628. if (!this.parent) {
  11629. return true;
  11630. }
  11631. if (this._parentRenderId !== this.parent._currentRenderId) {
  11632. return false;
  11633. }
  11634. return this.parent.isSynchronized();
  11635. };
  11636. Node.prototype.isSynchronized = function (updateCache) {
  11637. var check = this.hasNewParent();
  11638. check = check || !this.isSynchronizedWithParent();
  11639. check = check || !this._isSynchronized();
  11640. if (updateCache)
  11641. this.updateCache(true);
  11642. return !check;
  11643. };
  11644. Node.prototype.hasNewParent = function (update) {
  11645. if (this._cache.parent === this.parent)
  11646. return false;
  11647. if (update)
  11648. this._cache.parent = this.parent;
  11649. return true;
  11650. };
  11651. /**
  11652. * Is this node ready to be used/rendered
  11653. * @return {boolean} is it ready
  11654. */
  11655. Node.prototype.isReady = function () {
  11656. return this._isReady;
  11657. };
  11658. /**
  11659. * Is this node enabled.
  11660. * If the node has a parent and is enabled, the parent will be inspected as well.
  11661. * @return {boolean} whether this node (and its parent) is enabled.
  11662. * @see setEnabled
  11663. */
  11664. Node.prototype.isEnabled = function () {
  11665. if (!this._isEnabled) {
  11666. return false;
  11667. }
  11668. if (this.parent) {
  11669. return this.parent.isEnabled();
  11670. }
  11671. return true;
  11672. };
  11673. /**
  11674. * Set the enabled state of this node.
  11675. * @param {boolean} value - the new enabled state
  11676. * @see isEnabled
  11677. */
  11678. Node.prototype.setEnabled = function (value) {
  11679. this._isEnabled = value;
  11680. };
  11681. /**
  11682. * Is this node a descendant of the given node.
  11683. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11684. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11685. * @see parent
  11686. */
  11687. Node.prototype.isDescendantOf = function (ancestor) {
  11688. if (this.parent) {
  11689. if (this.parent === ancestor) {
  11690. return true;
  11691. }
  11692. return this.parent.isDescendantOf(ancestor);
  11693. }
  11694. return false;
  11695. };
  11696. /**
  11697. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11698. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11699. * @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.
  11700. * @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.
  11701. */
  11702. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11703. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11704. if (!this._children) {
  11705. return;
  11706. }
  11707. for (var index = 0; index < this._children.length; index++) {
  11708. var item = this._children[index];
  11709. if (!predicate || predicate(item)) {
  11710. results.push(item);
  11711. }
  11712. if (!directDescendantsOnly) {
  11713. item._getDescendants(results, false, predicate);
  11714. }
  11715. }
  11716. };
  11717. /**
  11718. * Will return all nodes that have this node as ascendant.
  11719. * @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.
  11720. * @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.
  11721. * @return {BABYLON.Node[]} all children nodes of all types.
  11722. */
  11723. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11724. var results = [];
  11725. this._getDescendants(results, directDescendantsOnly, predicate);
  11726. return results;
  11727. };
  11728. /**
  11729. * Get all child-meshes of this node.
  11730. */
  11731. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11732. var results = [];
  11733. this._getDescendants(results, directDecendantsOnly, function (node) {
  11734. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11735. });
  11736. return results;
  11737. };
  11738. /**
  11739. * Get all direct children of this node.
  11740. */
  11741. Node.prototype.getChildren = function (predicate) {
  11742. return this.getDescendants(true, predicate);
  11743. };
  11744. Node.prototype._setReady = function (state) {
  11745. if (state === this._isReady) {
  11746. return;
  11747. }
  11748. if (!state) {
  11749. this._isReady = false;
  11750. return;
  11751. }
  11752. this._isReady = true;
  11753. if (this.onReady) {
  11754. this.onReady(this);
  11755. }
  11756. };
  11757. Node.prototype.getAnimationByName = function (name) {
  11758. for (var i = 0; i < this.animations.length; i++) {
  11759. var animation = this.animations[i];
  11760. if (animation.name === name) {
  11761. return animation;
  11762. }
  11763. }
  11764. return null;
  11765. };
  11766. Node.prototype.createAnimationRange = function (name, from, to) {
  11767. // check name not already in use
  11768. if (!this._ranges[name]) {
  11769. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11770. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11771. if (this.animations[i]) {
  11772. this.animations[i].createRange(name, from, to);
  11773. }
  11774. }
  11775. }
  11776. };
  11777. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11778. if (deleteFrames === void 0) { deleteFrames = true; }
  11779. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11780. if (this.animations[i]) {
  11781. this.animations[i].deleteRange(name, deleteFrames);
  11782. }
  11783. }
  11784. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11785. };
  11786. Node.prototype.getAnimationRange = function (name) {
  11787. return this._ranges[name];
  11788. };
  11789. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11790. var range = this.getAnimationRange(name);
  11791. if (!range) {
  11792. return null;
  11793. }
  11794. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11795. };
  11796. Node.prototype.serializeAnimationRanges = function () {
  11797. var serializationRanges = [];
  11798. for (var name in this._ranges) {
  11799. var range = {};
  11800. range.name = name;
  11801. range.from = this._ranges[name].from;
  11802. range.to = this._ranges[name].to;
  11803. serializationRanges.push(range);
  11804. }
  11805. return serializationRanges;
  11806. };
  11807. Node.prototype.dispose = function () {
  11808. this.parent = null;
  11809. // Callback
  11810. this.onDisposeObservable.notifyObservers(this);
  11811. this.onDisposeObservable.clear();
  11812. // Behaviors
  11813. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11814. var behavior = _a[_i];
  11815. behavior.detach();
  11816. }
  11817. this._behaviors = [];
  11818. };
  11819. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11820. if (parsedNode.ranges) {
  11821. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11822. var data = parsedNode.ranges[index];
  11823. node.createAnimationRange(data.name, data.from, data.to);
  11824. }
  11825. }
  11826. };
  11827. return Node;
  11828. }());
  11829. __decorate([
  11830. BABYLON.serialize()
  11831. ], Node.prototype, "name", void 0);
  11832. __decorate([
  11833. BABYLON.serialize()
  11834. ], Node.prototype, "id", void 0);
  11835. __decorate([
  11836. BABYLON.serialize()
  11837. ], Node.prototype, "uniqueId", void 0);
  11838. __decorate([
  11839. BABYLON.serialize()
  11840. ], Node.prototype, "state", void 0);
  11841. __decorate([
  11842. BABYLON.serialize()
  11843. ], Node.prototype, "metadata", void 0);
  11844. BABYLON.Node = Node;
  11845. })(BABYLON || (BABYLON = {}));
  11846. //# sourceMappingURL=babylon.node.js.map
  11847. var BABYLON;
  11848. (function (BABYLON) {
  11849. var BoundingSphere = (function () {
  11850. function BoundingSphere(minimum, maximum) {
  11851. this.minimum = minimum;
  11852. this.maximum = maximum;
  11853. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11854. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11855. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11856. this.radius = distance * 0.5;
  11857. this.centerWorld = BABYLON.Vector3.Zero();
  11858. this._update(BABYLON.Matrix.Identity());
  11859. }
  11860. // Methods
  11861. BoundingSphere.prototype._update = function (world) {
  11862. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11863. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11864. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11865. };
  11866. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11867. for (var i = 0; i < 6; i++) {
  11868. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11869. return false;
  11870. }
  11871. return true;
  11872. };
  11873. BoundingSphere.prototype.intersectsPoint = function (point) {
  11874. var x = this.centerWorld.x - point.x;
  11875. var y = this.centerWorld.y - point.y;
  11876. var z = this.centerWorld.z - point.z;
  11877. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11878. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11879. return false;
  11880. return true;
  11881. };
  11882. // Statics
  11883. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11884. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11885. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11886. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11887. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11888. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11889. return false;
  11890. return true;
  11891. };
  11892. return BoundingSphere;
  11893. }());
  11894. BABYLON.BoundingSphere = BoundingSphere;
  11895. })(BABYLON || (BABYLON = {}));
  11896. //# sourceMappingURL=babylon.boundingSphere.js.map
  11897. var BABYLON;
  11898. (function (BABYLON) {
  11899. var BoundingBox = (function () {
  11900. function BoundingBox(minimum, maximum) {
  11901. this.minimum = minimum;
  11902. this.maximum = maximum;
  11903. this.vectors = new Array();
  11904. this.vectorsWorld = new Array();
  11905. // Bounding vectors
  11906. this.vectors.push(this.minimum.clone());
  11907. this.vectors.push(this.maximum.clone());
  11908. this.vectors.push(this.minimum.clone());
  11909. this.vectors[2].x = this.maximum.x;
  11910. this.vectors.push(this.minimum.clone());
  11911. this.vectors[3].y = this.maximum.y;
  11912. this.vectors.push(this.minimum.clone());
  11913. this.vectors[4].z = this.maximum.z;
  11914. this.vectors.push(this.maximum.clone());
  11915. this.vectors[5].z = this.minimum.z;
  11916. this.vectors.push(this.maximum.clone());
  11917. this.vectors[6].x = this.minimum.x;
  11918. this.vectors.push(this.maximum.clone());
  11919. this.vectors[7].y = this.minimum.y;
  11920. // OBB
  11921. this.center = this.maximum.add(this.minimum).scale(0.5);
  11922. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11923. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11924. // World
  11925. for (var index = 0; index < this.vectors.length; index++) {
  11926. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11927. }
  11928. this.minimumWorld = BABYLON.Vector3.Zero();
  11929. this.maximumWorld = BABYLON.Vector3.Zero();
  11930. this.centerWorld = BABYLON.Vector3.Zero();
  11931. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11932. this._update(BABYLON.Matrix.Identity());
  11933. }
  11934. // Methods
  11935. BoundingBox.prototype.getWorldMatrix = function () {
  11936. return this._worldMatrix;
  11937. };
  11938. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11939. this._worldMatrix.copyFrom(matrix);
  11940. return this;
  11941. };
  11942. BoundingBox.prototype._update = function (world) {
  11943. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11944. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11945. for (var index = 0; index < this.vectors.length; index++) {
  11946. var v = this.vectorsWorld[index];
  11947. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11948. if (v.x < this.minimumWorld.x)
  11949. this.minimumWorld.x = v.x;
  11950. if (v.y < this.minimumWorld.y)
  11951. this.minimumWorld.y = v.y;
  11952. if (v.z < this.minimumWorld.z)
  11953. this.minimumWorld.z = v.z;
  11954. if (v.x > this.maximumWorld.x)
  11955. this.maximumWorld.x = v.x;
  11956. if (v.y > this.maximumWorld.y)
  11957. this.maximumWorld.y = v.y;
  11958. if (v.z > this.maximumWorld.z)
  11959. this.maximumWorld.z = v.z;
  11960. }
  11961. // Extend
  11962. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11963. this.extendSizeWorld.scaleInPlace(0.5);
  11964. // OBB
  11965. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11966. this.centerWorld.scaleInPlace(0.5);
  11967. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11968. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11969. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11970. this._worldMatrix = world;
  11971. };
  11972. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11973. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11974. };
  11975. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11976. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11977. };
  11978. BoundingBox.prototype.intersectsPoint = function (point) {
  11979. var delta = -BABYLON.Epsilon;
  11980. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11981. return false;
  11982. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11983. return false;
  11984. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11985. return false;
  11986. return true;
  11987. };
  11988. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11989. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11990. };
  11991. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11992. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11993. return false;
  11994. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11995. return false;
  11996. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11997. return false;
  11998. return true;
  11999. };
  12000. // Statics
  12001. BoundingBox.Intersects = function (box0, box1) {
  12002. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12003. return false;
  12004. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12005. return false;
  12006. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12007. return false;
  12008. return true;
  12009. };
  12010. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12011. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12012. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12013. return (num <= (sphereRadius * sphereRadius));
  12014. };
  12015. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12016. for (var p = 0; p < 6; p++) {
  12017. for (var i = 0; i < 8; i++) {
  12018. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12019. return false;
  12020. }
  12021. }
  12022. }
  12023. return true;
  12024. };
  12025. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12026. for (var p = 0; p < 6; p++) {
  12027. var inCount = 8;
  12028. for (var i = 0; i < 8; i++) {
  12029. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12030. --inCount;
  12031. }
  12032. else {
  12033. break;
  12034. }
  12035. }
  12036. if (inCount === 0)
  12037. return false;
  12038. }
  12039. return true;
  12040. };
  12041. return BoundingBox;
  12042. }());
  12043. BABYLON.BoundingBox = BoundingBox;
  12044. })(BABYLON || (BABYLON = {}));
  12045. //# sourceMappingURL=babylon.boundingBox.js.map
  12046. var BABYLON;
  12047. (function (BABYLON) {
  12048. var computeBoxExtents = function (axis, box) {
  12049. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12050. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12051. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12052. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12053. var r = r0 + r1 + r2;
  12054. return {
  12055. min: p - r,
  12056. max: p + r
  12057. };
  12058. };
  12059. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12060. var axisOverlap = function (axis, box0, box1) {
  12061. var result0 = computeBoxExtents(axis, box0);
  12062. var result1 = computeBoxExtents(axis, box1);
  12063. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12064. };
  12065. var BoundingInfo = (function () {
  12066. function BoundingInfo(minimum, maximum) {
  12067. this.minimum = minimum;
  12068. this.maximum = maximum;
  12069. this._isLocked = false;
  12070. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12071. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12072. }
  12073. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12074. get: function () {
  12075. return this._isLocked;
  12076. },
  12077. set: function (value) {
  12078. this._isLocked = value;
  12079. },
  12080. enumerable: true,
  12081. configurable: true
  12082. });
  12083. // Methods
  12084. BoundingInfo.prototype.update = function (world) {
  12085. if (this._isLocked) {
  12086. return;
  12087. }
  12088. this.boundingBox._update(world);
  12089. this.boundingSphere._update(world);
  12090. };
  12091. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12092. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12093. return false;
  12094. return this.boundingBox.isInFrustum(frustumPlanes);
  12095. };
  12096. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12097. /**
  12098. * Gets the world distance between the min and max points of the bounding box
  12099. */
  12100. get: function () {
  12101. var boundingBox = this.boundingBox;
  12102. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12103. return size.length();
  12104. },
  12105. enumerable: true,
  12106. configurable: true
  12107. });
  12108. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12109. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12110. };
  12111. BoundingInfo.prototype._checkCollision = function (collider) {
  12112. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12113. };
  12114. BoundingInfo.prototype.intersectsPoint = function (point) {
  12115. if (!this.boundingSphere.centerWorld) {
  12116. return false;
  12117. }
  12118. if (!this.boundingSphere.intersectsPoint(point)) {
  12119. return false;
  12120. }
  12121. if (!this.boundingBox.intersectsPoint(point)) {
  12122. return false;
  12123. }
  12124. return true;
  12125. };
  12126. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12127. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12128. return false;
  12129. }
  12130. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12131. return false;
  12132. }
  12133. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12134. return false;
  12135. }
  12136. if (!precise) {
  12137. return true;
  12138. }
  12139. var box0 = this.boundingBox;
  12140. var box1 = boundingInfo.boundingBox;
  12141. if (!axisOverlap(box0.directions[0], box0, box1))
  12142. return false;
  12143. if (!axisOverlap(box0.directions[1], box0, box1))
  12144. return false;
  12145. if (!axisOverlap(box0.directions[2], box0, box1))
  12146. return false;
  12147. if (!axisOverlap(box1.directions[0], box0, box1))
  12148. return false;
  12149. if (!axisOverlap(box1.directions[1], box0, box1))
  12150. return false;
  12151. if (!axisOverlap(box1.directions[2], box0, box1))
  12152. return false;
  12153. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12154. return false;
  12155. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12156. return false;
  12157. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12158. return false;
  12159. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12160. return false;
  12161. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12162. return false;
  12163. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12164. return false;
  12165. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12166. return false;
  12167. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12168. return false;
  12169. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12170. return false;
  12171. return true;
  12172. };
  12173. return BoundingInfo;
  12174. }());
  12175. BABYLON.BoundingInfo = BoundingInfo;
  12176. })(BABYLON || (BABYLON = {}));
  12177. //# sourceMappingURL=babylon.boundingInfo.js.map
  12178. var BABYLON;
  12179. (function (BABYLON) {
  12180. var AbstractMesh = (function (_super) {
  12181. __extends(AbstractMesh, _super);
  12182. // Constructor
  12183. function AbstractMesh(name, scene) {
  12184. var _this = _super.call(this, name, scene) || this;
  12185. _this._facetNb = 0; // facet number
  12186. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12187. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12188. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12189. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12190. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12191. _this._subDiv = {
  12192. max: 1,
  12193. X: 1,
  12194. Y: 1,
  12195. Z: 1
  12196. };
  12197. // Events
  12198. /**
  12199. * An event triggered when this mesh collides with another one
  12200. * @type {BABYLON.Observable}
  12201. */
  12202. _this.onCollideObservable = new BABYLON.Observable();
  12203. /**
  12204. * An event triggered when the collision's position changes
  12205. * @type {BABYLON.Observable}
  12206. */
  12207. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12208. /**
  12209. * An event triggered after the world matrix is updated
  12210. * @type {BABYLON.Observable}
  12211. */
  12212. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12213. /**
  12214. * An event triggered when material is changed
  12215. * @type {BABYLON.Observable}
  12216. */
  12217. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12218. // Properties
  12219. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12220. _this.position = BABYLON.Vector3.Zero();
  12221. /**
  12222. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12223. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12224. * or
  12225. * 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.
  12226. * for more info check WebGl documentations
  12227. */
  12228. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12229. /**
  12230. * 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:
  12231. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12232. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12233. * 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.
  12234. */
  12235. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12236. /**
  12237. * 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.
  12238. * The default value is -1 which means don't break the query and wait till the result.
  12239. */
  12240. _this.occlusionRetryCount = -1;
  12241. _this._occlusionInternalRetryCounter = 0;
  12242. _this._isOccluded = false;
  12243. _this._isOcclusionQueryInProgress = false;
  12244. _this._rotation = BABYLON.Vector3.Zero();
  12245. _this._scaling = BABYLON.Vector3.One();
  12246. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12247. _this.visibility = 1.0;
  12248. _this.alphaIndex = Number.MAX_VALUE;
  12249. _this.infiniteDistance = false;
  12250. _this.isVisible = true;
  12251. _this.isPickable = true;
  12252. _this.showBoundingBox = false;
  12253. _this.showSubMeshesBoundingBox = false;
  12254. _this.isBlocker = false;
  12255. _this.enablePointerMoveEvents = false;
  12256. _this.renderingGroupId = 0;
  12257. _this._receiveShadows = false;
  12258. _this.renderOutline = false;
  12259. _this.outlineColor = BABYLON.Color3.Red();
  12260. _this.outlineWidth = 0.02;
  12261. _this.renderOverlay = false;
  12262. _this.overlayColor = BABYLON.Color3.Red();
  12263. _this.overlayAlpha = 0.5;
  12264. _this._hasVertexAlpha = false;
  12265. _this._useVertexColors = true;
  12266. _this._computeBonesUsingShaders = true;
  12267. _this._numBoneInfluencers = 4;
  12268. _this._applyFog = true;
  12269. _this.scalingDeterminant = 1;
  12270. _this.useOctreeForRenderingSelection = true;
  12271. _this.useOctreeForPicking = true;
  12272. _this.useOctreeForCollisions = true;
  12273. _this._layerMask = 0x0FFFFFFF;
  12274. /**
  12275. * True if the mesh must be rendered in any case.
  12276. */
  12277. _this.alwaysSelectAsActiveMesh = false;
  12278. // Collisions
  12279. _this._checkCollisions = false;
  12280. _this._collisionMask = -1;
  12281. _this._collisionGroup = -1;
  12282. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12283. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12284. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12285. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12286. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12287. // Edges
  12288. _this.edgesWidth = 1;
  12289. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12290. // Cache
  12291. _this._localWorld = BABYLON.Matrix.Zero();
  12292. _this._worldMatrix = BABYLON.Matrix.Zero();
  12293. _this._absolutePosition = BABYLON.Vector3.Zero();
  12294. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12295. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12296. _this._isDirty = false;
  12297. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12298. _this._isDisposed = false;
  12299. _this._renderId = 0;
  12300. _this._intersectionsInProgress = new Array();
  12301. _this._isWorldMatrixFrozen = false;
  12302. _this._unIndexed = false;
  12303. _this._lightSources = new Array();
  12304. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12305. if (collidedMesh === void 0) { collidedMesh = null; }
  12306. //TODO move this to the collision coordinator!
  12307. if (_this.getScene().workerCollisions)
  12308. newPosition.multiplyInPlace(_this._collider.radius);
  12309. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12310. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12311. _this.position.addInPlace(_this._diffPositionForCollisions);
  12312. }
  12313. if (collidedMesh) {
  12314. _this.onCollideObservable.notifyObservers(collidedMesh);
  12315. }
  12316. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12317. };
  12318. _this.getScene().addMesh(_this);
  12319. _this._resyncLightSources();
  12320. return _this;
  12321. }
  12322. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12323. get: function () {
  12324. return AbstractMesh._BILLBOARDMODE_NONE;
  12325. },
  12326. enumerable: true,
  12327. configurable: true
  12328. });
  12329. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12330. get: function () {
  12331. return AbstractMesh._BILLBOARDMODE_X;
  12332. },
  12333. enumerable: true,
  12334. configurable: true
  12335. });
  12336. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12337. get: function () {
  12338. return AbstractMesh._BILLBOARDMODE_Y;
  12339. },
  12340. enumerable: true,
  12341. configurable: true
  12342. });
  12343. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12344. get: function () {
  12345. return AbstractMesh._BILLBOARDMODE_Z;
  12346. },
  12347. enumerable: true,
  12348. configurable: true
  12349. });
  12350. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12351. get: function () {
  12352. return AbstractMesh._BILLBOARDMODE_ALL;
  12353. },
  12354. enumerable: true,
  12355. configurable: true
  12356. });
  12357. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12358. /**
  12359. * Read-only : the number of facets in the mesh
  12360. */
  12361. get: function () {
  12362. return this._facetNb;
  12363. },
  12364. enumerable: true,
  12365. configurable: true
  12366. });
  12367. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12368. /**
  12369. * The number (integer) of subdivisions per axis in the partioning space
  12370. */
  12371. get: function () {
  12372. return this._partitioningSubdivisions;
  12373. },
  12374. set: function (nb) {
  12375. this._partitioningSubdivisions = nb;
  12376. },
  12377. enumerable: true,
  12378. configurable: true
  12379. });
  12380. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12381. /**
  12382. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12383. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12384. */
  12385. get: function () {
  12386. return this._partitioningBBoxRatio;
  12387. },
  12388. set: function (ratio) {
  12389. this._partitioningBBoxRatio = ratio;
  12390. },
  12391. enumerable: true,
  12392. configurable: true
  12393. });
  12394. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12395. /**
  12396. * Read-only boolean : is the feature facetData enabled ?
  12397. */
  12398. get: function () {
  12399. return this._facetDataEnabled;
  12400. },
  12401. enumerable: true,
  12402. configurable: true
  12403. });
  12404. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12405. set: function (callback) {
  12406. if (this._onCollideObserver) {
  12407. this.onCollideObservable.remove(this._onCollideObserver);
  12408. }
  12409. this._onCollideObserver = this.onCollideObservable.add(callback);
  12410. },
  12411. enumerable: true,
  12412. configurable: true
  12413. });
  12414. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12415. set: function (callback) {
  12416. if (this._onCollisionPositionChangeObserver) {
  12417. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12418. }
  12419. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12420. },
  12421. enumerable: true,
  12422. configurable: true
  12423. });
  12424. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12425. /**
  12426. * 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.
  12427. */
  12428. get: function () {
  12429. return this._isOccluded;
  12430. },
  12431. set: function (value) {
  12432. this._isOccluded = value;
  12433. },
  12434. enumerable: true,
  12435. configurable: true
  12436. });
  12437. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12438. /**
  12439. * Flag to check the progress status of the query
  12440. */
  12441. get: function () {
  12442. return this._isOcclusionQueryInProgress;
  12443. },
  12444. enumerable: true,
  12445. configurable: true
  12446. });
  12447. Object.defineProperty(AbstractMesh.prototype, "material", {
  12448. get: function () {
  12449. return this._material;
  12450. },
  12451. set: function (value) {
  12452. if (this._material === value) {
  12453. return;
  12454. }
  12455. this._material = value;
  12456. if (this.onMaterialChangedObservable.hasObservers) {
  12457. this.onMaterialChangedObservable.notifyObservers(this);
  12458. }
  12459. if (!this.subMeshes) {
  12460. return;
  12461. }
  12462. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12463. var subMesh = _a[_i];
  12464. subMesh.setEffect(null);
  12465. }
  12466. },
  12467. enumerable: true,
  12468. configurable: true
  12469. });
  12470. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12471. get: function () {
  12472. return this._receiveShadows;
  12473. },
  12474. set: function (value) {
  12475. if (this._receiveShadows === value) {
  12476. return;
  12477. }
  12478. this._receiveShadows = value;
  12479. this._markSubMeshesAsLightDirty();
  12480. },
  12481. enumerable: true,
  12482. configurable: true
  12483. });
  12484. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12485. get: function () {
  12486. return this._hasVertexAlpha;
  12487. },
  12488. set: function (value) {
  12489. if (this._hasVertexAlpha === value) {
  12490. return;
  12491. }
  12492. this._hasVertexAlpha = value;
  12493. this._markSubMeshesAsAttributesDirty();
  12494. },
  12495. enumerable: true,
  12496. configurable: true
  12497. });
  12498. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12499. get: function () {
  12500. return this._useVertexColors;
  12501. },
  12502. set: function (value) {
  12503. if (this._useVertexColors === value) {
  12504. return;
  12505. }
  12506. this._useVertexColors = value;
  12507. this._markSubMeshesAsAttributesDirty();
  12508. },
  12509. enumerable: true,
  12510. configurable: true
  12511. });
  12512. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12513. get: function () {
  12514. return this._computeBonesUsingShaders;
  12515. },
  12516. set: function (value) {
  12517. if (this._computeBonesUsingShaders === value) {
  12518. return;
  12519. }
  12520. this._computeBonesUsingShaders = value;
  12521. this._markSubMeshesAsAttributesDirty();
  12522. },
  12523. enumerable: true,
  12524. configurable: true
  12525. });
  12526. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12527. get: function () {
  12528. return this._numBoneInfluencers;
  12529. },
  12530. set: function (value) {
  12531. if (this._numBoneInfluencers === value) {
  12532. return;
  12533. }
  12534. this._numBoneInfluencers = value;
  12535. this._markSubMeshesAsAttributesDirty();
  12536. },
  12537. enumerable: true,
  12538. configurable: true
  12539. });
  12540. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12541. get: function () {
  12542. return this._applyFog;
  12543. },
  12544. set: function (value) {
  12545. if (this._applyFog === value) {
  12546. return;
  12547. }
  12548. this._applyFog = value;
  12549. this._markSubMeshesAsMiscDirty();
  12550. },
  12551. enumerable: true,
  12552. configurable: true
  12553. });
  12554. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12555. get: function () {
  12556. return this._layerMask;
  12557. },
  12558. set: function (value) {
  12559. if (value === this._layerMask) {
  12560. return;
  12561. }
  12562. this._layerMask = value;
  12563. this._resyncLightSources();
  12564. },
  12565. enumerable: true,
  12566. configurable: true
  12567. });
  12568. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12569. get: function () {
  12570. return this._collisionMask;
  12571. },
  12572. set: function (mask) {
  12573. this._collisionMask = !isNaN(mask) ? mask : -1;
  12574. },
  12575. enumerable: true,
  12576. configurable: true
  12577. });
  12578. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12579. get: function () {
  12580. return this._collisionGroup;
  12581. },
  12582. set: function (mask) {
  12583. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12584. },
  12585. enumerable: true,
  12586. configurable: true
  12587. });
  12588. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12589. get: function () {
  12590. return null;
  12591. },
  12592. enumerable: true,
  12593. configurable: true
  12594. });
  12595. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12596. get: function () {
  12597. return this._skeleton;
  12598. },
  12599. set: function (value) {
  12600. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12601. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12602. }
  12603. if (value && value.needInitialSkinMatrix) {
  12604. value._registerMeshWithPoseMatrix(this);
  12605. }
  12606. this._skeleton = value;
  12607. if (!this._skeleton) {
  12608. this._bonesTransformMatrices = null;
  12609. }
  12610. this._markSubMeshesAsAttributesDirty();
  12611. },
  12612. enumerable: true,
  12613. configurable: true
  12614. });
  12615. /**
  12616. * Boolean : true if the mesh has been disposed.
  12617. */
  12618. AbstractMesh.prototype.isDisposed = function () {
  12619. return this._isDisposed;
  12620. };
  12621. /**
  12622. * Returns the string "AbstractMesh"
  12623. */
  12624. AbstractMesh.prototype.getClassName = function () {
  12625. return "AbstractMesh";
  12626. };
  12627. /**
  12628. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12629. */
  12630. AbstractMesh.prototype.toString = function (fullDetails) {
  12631. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12632. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12633. if (this._skeleton) {
  12634. ret += ", skeleton: " + this._skeleton.name;
  12635. }
  12636. if (fullDetails) {
  12637. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12638. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12639. }
  12640. return ret;
  12641. };
  12642. AbstractMesh.prototype._rebuild = function () {
  12643. if (this._occlusionQuery) {
  12644. this._occlusionQuery = null;
  12645. }
  12646. if (this._edgesRenderer) {
  12647. this._edgesRenderer._rebuild();
  12648. }
  12649. if (!this.subMeshes) {
  12650. return;
  12651. }
  12652. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12653. var subMesh = _a[_i];
  12654. subMesh._rebuild();
  12655. }
  12656. };
  12657. AbstractMesh.prototype._resyncLightSources = function () {
  12658. this._lightSources.length = 0;
  12659. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12660. var light = _a[_i];
  12661. if (!light.isEnabled()) {
  12662. continue;
  12663. }
  12664. if (light.canAffectMesh(this)) {
  12665. this._lightSources.push(light);
  12666. }
  12667. }
  12668. this._markSubMeshesAsLightDirty();
  12669. };
  12670. AbstractMesh.prototype._resyncLighSource = function (light) {
  12671. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12672. var index = this._lightSources.indexOf(light);
  12673. if (index === -1) {
  12674. if (!isIn) {
  12675. return;
  12676. }
  12677. this._lightSources.push(light);
  12678. }
  12679. else {
  12680. if (isIn) {
  12681. return;
  12682. }
  12683. this._lightSources.splice(index, 1);
  12684. }
  12685. this._markSubMeshesAsLightDirty();
  12686. };
  12687. AbstractMesh.prototype._removeLightSource = function (light) {
  12688. var index = this._lightSources.indexOf(light);
  12689. if (index === -1) {
  12690. return;
  12691. }
  12692. this._lightSources.splice(index, 1);
  12693. };
  12694. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12695. if (!this.subMeshes) {
  12696. return;
  12697. }
  12698. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12699. var subMesh = _a[_i];
  12700. if (subMesh._materialDefines) {
  12701. func(subMesh._materialDefines);
  12702. }
  12703. }
  12704. };
  12705. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12706. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12707. };
  12708. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12709. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12710. };
  12711. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12712. if (!this.subMeshes) {
  12713. return;
  12714. }
  12715. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12716. var subMesh = _a[_i];
  12717. var material = subMesh.getMaterial();
  12718. if (material) {
  12719. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12720. }
  12721. }
  12722. };
  12723. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12724. /**
  12725. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12726. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12727. * Default : (0.0, 0.0, 0.0)
  12728. */
  12729. get: function () {
  12730. return this._rotation;
  12731. },
  12732. set: function (newRotation) {
  12733. this._rotation = newRotation;
  12734. },
  12735. enumerable: true,
  12736. configurable: true
  12737. });
  12738. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12739. /**
  12740. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12741. * Default : (1.0, 1.0, 1.0)
  12742. */
  12743. get: function () {
  12744. return this._scaling;
  12745. },
  12746. set: function (newScaling) {
  12747. this._scaling = newScaling;
  12748. if (this.physicsImpostor) {
  12749. this.physicsImpostor.forceUpdate();
  12750. }
  12751. },
  12752. enumerable: true,
  12753. configurable: true
  12754. });
  12755. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12756. /**
  12757. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12758. * It's null by default.
  12759. * 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)
  12760. */
  12761. get: function () {
  12762. return this._rotationQuaternion;
  12763. },
  12764. set: function (quaternion) {
  12765. this._rotationQuaternion = quaternion;
  12766. //reset the rotation vector.
  12767. if (quaternion && this.rotation.length()) {
  12768. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12769. }
  12770. },
  12771. enumerable: true,
  12772. configurable: true
  12773. });
  12774. // Methods
  12775. /**
  12776. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12777. * Returns the AbstractMesh.
  12778. */
  12779. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12780. this._poseMatrix.copyFrom(matrix);
  12781. return this;
  12782. };
  12783. /**
  12784. * Returns the mesh Pose matrix.
  12785. * Returned object : Matrix
  12786. */
  12787. AbstractMesh.prototype.getPoseMatrix = function () {
  12788. return this._poseMatrix;
  12789. };
  12790. /**
  12791. * Disables the mesh edger rendering mode.
  12792. * Returns the AbstractMesh.
  12793. */
  12794. AbstractMesh.prototype.disableEdgesRendering = function () {
  12795. if (this._edgesRenderer !== undefined) {
  12796. this._edgesRenderer.dispose();
  12797. this._edgesRenderer = undefined;
  12798. }
  12799. return this;
  12800. };
  12801. /**
  12802. * Enables the edge rendering mode on the mesh.
  12803. * This mode makes the mesh edges visible.
  12804. * Returns the AbstractMesh.
  12805. */
  12806. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12807. if (epsilon === void 0) { epsilon = 0.95; }
  12808. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12809. this.disableEdgesRendering();
  12810. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12811. return this;
  12812. };
  12813. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12814. /**
  12815. * Returns true if the mesh is blocked. Used by the class Mesh.
  12816. * Returns the boolean `false` by default.
  12817. */
  12818. get: function () {
  12819. return false;
  12820. },
  12821. enumerable: true,
  12822. configurable: true
  12823. });
  12824. /**
  12825. * Returns the mesh itself by default, used by the class Mesh.
  12826. * Returned type : AbstractMesh
  12827. */
  12828. AbstractMesh.prototype.getLOD = function (camera) {
  12829. return this;
  12830. };
  12831. /**
  12832. * Returns 0 by default, used by the class Mesh.
  12833. * Returns an integer.
  12834. */
  12835. AbstractMesh.prototype.getTotalVertices = function () {
  12836. return 0;
  12837. };
  12838. /**
  12839. * Returns null by default, used by the class Mesh.
  12840. * Returned type : integer array
  12841. */
  12842. AbstractMesh.prototype.getIndices = function () {
  12843. return null;
  12844. };
  12845. /**
  12846. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12847. * Returned type : float array or Float32Array
  12848. */
  12849. AbstractMesh.prototype.getVerticesData = function (kind) {
  12850. return null;
  12851. };
  12852. /**
  12853. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12854. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12855. * The `data` are either a numeric array either a Float32Array.
  12856. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12857. * 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).
  12858. * Note that a new underlying VertexBuffer object is created each call.
  12859. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12860. *
  12861. * Possible `kind` values :
  12862. * - BABYLON.VertexBuffer.PositionKind
  12863. * - BABYLON.VertexBuffer.UVKind
  12864. * - BABYLON.VertexBuffer.UV2Kind
  12865. * - BABYLON.VertexBuffer.UV3Kind
  12866. * - BABYLON.VertexBuffer.UV4Kind
  12867. * - BABYLON.VertexBuffer.UV5Kind
  12868. * - BABYLON.VertexBuffer.UV6Kind
  12869. * - BABYLON.VertexBuffer.ColorKind
  12870. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12871. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12872. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12873. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12874. *
  12875. * Returns the Mesh.
  12876. */
  12877. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12878. return null;
  12879. };
  12880. /**
  12881. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12882. * If the mesh has no geometry, it is simply returned as it is.
  12883. * The `data` are either a numeric array either a Float32Array.
  12884. * No new underlying VertexBuffer object is created.
  12885. * 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.
  12886. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12887. *
  12888. * Possible `kind` values :
  12889. * - BABYLON.VertexBuffer.PositionKind
  12890. * - BABYLON.VertexBuffer.UVKind
  12891. * - BABYLON.VertexBuffer.UV2Kind
  12892. * - BABYLON.VertexBuffer.UV3Kind
  12893. * - BABYLON.VertexBuffer.UV4Kind
  12894. * - BABYLON.VertexBuffer.UV5Kind
  12895. * - BABYLON.VertexBuffer.UV6Kind
  12896. * - BABYLON.VertexBuffer.ColorKind
  12897. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12898. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12899. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12900. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12901. *
  12902. * Returns the Mesh.
  12903. */
  12904. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12905. return null;
  12906. };
  12907. /**
  12908. * Sets the mesh indices.
  12909. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12910. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12911. * This method creates a new index buffer each call.
  12912. * Returns the Mesh.
  12913. */
  12914. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12915. return null;
  12916. };
  12917. /** Returns false by default, used by the class Mesh.
  12918. * Returns a boolean
  12919. */
  12920. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12921. return false;
  12922. };
  12923. /**
  12924. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12925. * Returns a BoundingInfo
  12926. */
  12927. AbstractMesh.prototype.getBoundingInfo = function () {
  12928. if (this._masterMesh) {
  12929. return this._masterMesh.getBoundingInfo();
  12930. }
  12931. if (!this._boundingInfo) {
  12932. this._updateBoundingInfo();
  12933. }
  12934. return this._boundingInfo;
  12935. };
  12936. /**
  12937. * Sets a mesh new object BoundingInfo.
  12938. * Returns the AbstractMesh.
  12939. */
  12940. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12941. this._boundingInfo = boundingInfo;
  12942. return this;
  12943. };
  12944. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12945. get: function () {
  12946. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12947. },
  12948. enumerable: true,
  12949. configurable: true
  12950. });
  12951. AbstractMesh.prototype._preActivate = function () {
  12952. };
  12953. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12954. };
  12955. AbstractMesh.prototype._activate = function (renderId) {
  12956. this._renderId = renderId;
  12957. };
  12958. /**
  12959. * Returns the last update of the World matrix
  12960. * Returns a Matrix.
  12961. */
  12962. AbstractMesh.prototype.getWorldMatrix = function () {
  12963. if (this._masterMesh) {
  12964. return this._masterMesh.getWorldMatrix();
  12965. }
  12966. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12967. this.computeWorldMatrix();
  12968. }
  12969. return this._worldMatrix;
  12970. };
  12971. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12972. /**
  12973. * Returns directly the last state of the mesh World matrix.
  12974. * A Matrix is returned.
  12975. */
  12976. get: function () {
  12977. return this._worldMatrix;
  12978. },
  12979. enumerable: true,
  12980. configurable: true
  12981. });
  12982. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12983. /**
  12984. * Returns the current mesh absolute position.
  12985. * Retuns a Vector3.
  12986. */
  12987. get: function () {
  12988. return this._absolutePosition;
  12989. },
  12990. enumerable: true,
  12991. configurable: true
  12992. });
  12993. /**
  12994. * Prevents the World matrix to be computed any longer.
  12995. * Returns the AbstractMesh.
  12996. */
  12997. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12998. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12999. this.computeWorldMatrix(true);
  13000. this._isWorldMatrixFrozen = true;
  13001. return this;
  13002. };
  13003. /**
  13004. * Allows back the World matrix computation.
  13005. * Returns the AbstractMesh.
  13006. */
  13007. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13008. this._isWorldMatrixFrozen = false;
  13009. this.computeWorldMatrix(true);
  13010. return this;
  13011. };
  13012. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13013. /**
  13014. * True if the World matrix has been frozen.
  13015. * Returns a boolean.
  13016. */
  13017. get: function () {
  13018. return this._isWorldMatrixFrozen;
  13019. },
  13020. enumerable: true,
  13021. configurable: true
  13022. });
  13023. /**
  13024. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13025. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13026. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13027. * The passed axis is also normalized.
  13028. * Returns the AbstractMesh.
  13029. */
  13030. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13031. axis.normalize();
  13032. if (!this.rotationQuaternion) {
  13033. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13034. this.rotation = BABYLON.Vector3.Zero();
  13035. }
  13036. var rotationQuaternion;
  13037. if (!space || space === BABYLON.Space.LOCAL) {
  13038. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13039. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13040. }
  13041. else {
  13042. if (this.parent) {
  13043. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13044. invertParentWorldMatrix.invert();
  13045. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13046. }
  13047. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13048. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13049. }
  13050. return this;
  13051. };
  13052. /**
  13053. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13054. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13055. * The passed axis is also normalized.
  13056. * Returns the AbstractMesh.
  13057. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13058. */
  13059. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13060. axis.normalize();
  13061. if (!this.rotationQuaternion) {
  13062. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13063. this.rotation.copyFromFloats(0, 0, 0);
  13064. }
  13065. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13066. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13067. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13068. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13069. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13070. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13071. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13072. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13073. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13074. return this;
  13075. };
  13076. /**
  13077. * Translates the mesh along the axis vector for the passed distance in the given space.
  13078. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13079. * Returns the AbstractMesh.
  13080. */
  13081. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13082. var displacementVector = axis.scale(distance);
  13083. if (!space || space === BABYLON.Space.LOCAL) {
  13084. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13085. this.setPositionWithLocalVector(tempV3);
  13086. }
  13087. else {
  13088. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13089. }
  13090. return this;
  13091. };
  13092. /**
  13093. * Adds a rotation step to the mesh current rotation.
  13094. * x, y, z are Euler angles expressed in radians.
  13095. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13096. * This means this rotation is made in the mesh local space only.
  13097. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13098. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13099. * ```javascript
  13100. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13101. * ```
  13102. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13103. * 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.
  13104. * Returns the AbstractMesh.
  13105. */
  13106. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13107. var rotationQuaternion;
  13108. if (this.rotationQuaternion) {
  13109. rotationQuaternion = this.rotationQuaternion;
  13110. }
  13111. else {
  13112. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13113. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13114. }
  13115. var accumulation = BABYLON.Tmp.Quaternion[0];
  13116. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13117. rotationQuaternion.multiplyInPlace(accumulation);
  13118. if (!this.rotationQuaternion) {
  13119. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13120. }
  13121. return this;
  13122. };
  13123. /**
  13124. * Retuns the mesh absolute position in the World.
  13125. * Returns a Vector3.
  13126. */
  13127. AbstractMesh.prototype.getAbsolutePosition = function () {
  13128. this.computeWorldMatrix();
  13129. return this._absolutePosition;
  13130. };
  13131. /**
  13132. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13133. * Returns the AbstractMesh.
  13134. */
  13135. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13136. if (!absolutePosition) {
  13137. return;
  13138. }
  13139. var absolutePositionX;
  13140. var absolutePositionY;
  13141. var absolutePositionZ;
  13142. if (absolutePosition.x === undefined) {
  13143. if (arguments.length < 3) {
  13144. return;
  13145. }
  13146. absolutePositionX = arguments[0];
  13147. absolutePositionY = arguments[1];
  13148. absolutePositionZ = arguments[2];
  13149. }
  13150. else {
  13151. absolutePositionX = absolutePosition.x;
  13152. absolutePositionY = absolutePosition.y;
  13153. absolutePositionZ = absolutePosition.z;
  13154. }
  13155. if (this.parent) {
  13156. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13157. invertParentWorldMatrix.invert();
  13158. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13159. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13160. }
  13161. else {
  13162. this.position.x = absolutePositionX;
  13163. this.position.y = absolutePositionY;
  13164. this.position.z = absolutePositionZ;
  13165. }
  13166. return this;
  13167. };
  13168. // ================================== Point of View Movement =================================
  13169. /**
  13170. * Perform relative position change from the point of view of behind the front of the mesh.
  13171. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13172. * Supports definition of mesh facing forward or backward.
  13173. * @param {number} amountRight
  13174. * @param {number} amountUp
  13175. * @param {number} amountForward
  13176. *
  13177. * Returns the AbstractMesh.
  13178. */
  13179. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13180. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13181. return this;
  13182. };
  13183. /**
  13184. * Calculate relative position change from the point of view of behind the front of the mesh.
  13185. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13186. * Supports definition of mesh facing forward or backward.
  13187. * @param {number} amountRight
  13188. * @param {number} amountUp
  13189. * @param {number} amountForward
  13190. *
  13191. * Returns a new Vector3.
  13192. */
  13193. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13194. var rotMatrix = new BABYLON.Matrix();
  13195. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13196. rotQuaternion.toRotationMatrix(rotMatrix);
  13197. var translationDelta = BABYLON.Vector3.Zero();
  13198. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13199. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13200. return translationDelta;
  13201. };
  13202. // ================================== Point of View Rotation =================================
  13203. /**
  13204. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13205. * Supports definition of mesh facing forward or backward.
  13206. * @param {number} flipBack
  13207. * @param {number} twirlClockwise
  13208. * @param {number} tiltRight
  13209. *
  13210. * Returns the AbstractMesh.
  13211. */
  13212. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13213. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13214. return this;
  13215. };
  13216. /**
  13217. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13218. * Supports definition of mesh facing forward or backward.
  13219. * @param {number} flipBack
  13220. * @param {number} twirlClockwise
  13221. * @param {number} tiltRight
  13222. *
  13223. * Returns a new Vector3.
  13224. */
  13225. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13226. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13227. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13228. };
  13229. /**
  13230. * Sets a new pivot matrix to the mesh.
  13231. * Returns the AbstractMesh.
  13232. */
  13233. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  13234. this._pivotMatrix = matrix;
  13235. this._cache.pivotMatrixUpdated = true;
  13236. return this;
  13237. };
  13238. /**
  13239. * Returns the mesh pivot matrix.
  13240. * Default : Identity.
  13241. * A Matrix is returned.
  13242. */
  13243. AbstractMesh.prototype.getPivotMatrix = function () {
  13244. return this._pivotMatrix;
  13245. };
  13246. AbstractMesh.prototype._isSynchronized = function () {
  13247. if (this._isDirty) {
  13248. return false;
  13249. }
  13250. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13251. return false;
  13252. if (this._cache.pivotMatrixUpdated) {
  13253. return false;
  13254. }
  13255. if (this.infiniteDistance) {
  13256. return false;
  13257. }
  13258. if (!this._cache.position.equals(this.position))
  13259. return false;
  13260. if (this.rotationQuaternion) {
  13261. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13262. return false;
  13263. }
  13264. if (!this._cache.rotation.equals(this.rotation))
  13265. return false;
  13266. if (!this._cache.scaling.equals(this.scaling))
  13267. return false;
  13268. return true;
  13269. };
  13270. AbstractMesh.prototype._initCache = function () {
  13271. _super.prototype._initCache.call(this);
  13272. this._cache.localMatrixUpdated = false;
  13273. this._cache.position = BABYLON.Vector3.Zero();
  13274. this._cache.scaling = BABYLON.Vector3.Zero();
  13275. this._cache.rotation = BABYLON.Vector3.Zero();
  13276. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13277. this._cache.billboardMode = -1;
  13278. };
  13279. AbstractMesh.prototype.markAsDirty = function (property) {
  13280. if (property === "rotation") {
  13281. this.rotationQuaternion = null;
  13282. }
  13283. this._currentRenderId = Number.MAX_VALUE;
  13284. this._isDirty = true;
  13285. return this;
  13286. };
  13287. /**
  13288. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  13289. */
  13290. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  13291. this.computeWorldMatrix(true);
  13292. var min;
  13293. var max;
  13294. if (!this.subMeshes) {
  13295. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13296. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13297. }
  13298. else {
  13299. min = this.getBoundingInfo().boundingBox.minimumWorld;
  13300. max = this.getBoundingInfo().boundingBox.maximumWorld;
  13301. }
  13302. var descendants = this.getDescendants(false);
  13303. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  13304. var descendant = descendants_1[_i];
  13305. var childMesh = descendant;
  13306. childMesh.computeWorldMatrix(true);
  13307. if (childMesh.getTotalVertices() === 0) {
  13308. continue;
  13309. }
  13310. var boundingBox = childMesh.getBoundingInfo().boundingBox;
  13311. var minBox = boundingBox.minimumWorld;
  13312. var maxBox = boundingBox.maximumWorld;
  13313. BABYLON.Tools.CheckExtends(minBox, min, max);
  13314. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13315. }
  13316. return {
  13317. min: min,
  13318. max: max
  13319. };
  13320. };
  13321. /**
  13322. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13323. * Returns the AbstractMesh.
  13324. */
  13325. AbstractMesh.prototype._updateBoundingInfo = function () {
  13326. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13327. this._boundingInfo.update(this.worldMatrixFromCache);
  13328. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13329. return this;
  13330. };
  13331. /**
  13332. * Update a mesh's children BoundingInfo objects only.
  13333. * Returns the AbstractMesh.
  13334. */
  13335. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13336. if (!this.subMeshes) {
  13337. return;
  13338. }
  13339. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13340. var subMesh = this.subMeshes[subIndex];
  13341. if (!subMesh.IsGlobal) {
  13342. subMesh.updateBoundingInfo(matrix);
  13343. }
  13344. }
  13345. return this;
  13346. };
  13347. /**
  13348. * Computes the mesh World matrix and returns it.
  13349. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13350. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13351. * If the parameter `force`is set to `true`, the actual computation is done.
  13352. * Returns the mesh World Matrix.
  13353. */
  13354. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13355. if (this._isWorldMatrixFrozen) {
  13356. return this._worldMatrix;
  13357. }
  13358. if (!force && this.isSynchronized(true)) {
  13359. this._currentRenderId = this.getScene().getRenderId();
  13360. return this._worldMatrix;
  13361. }
  13362. this._cache.position.copyFrom(this.position);
  13363. this._cache.scaling.copyFrom(this.scaling);
  13364. this._cache.pivotMatrixUpdated = false;
  13365. this._cache.billboardMode = this.billboardMode;
  13366. this._currentRenderId = this.getScene().getRenderId();
  13367. this._isDirty = false;
  13368. // Scaling
  13369. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13370. // Rotation
  13371. //rotate, if quaternion is set and rotation was used
  13372. if (this.rotationQuaternion) {
  13373. var len = this.rotation.length();
  13374. if (len) {
  13375. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13376. this.rotation.copyFromFloats(0, 0, 0);
  13377. }
  13378. }
  13379. if (this.rotationQuaternion) {
  13380. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13381. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13382. }
  13383. else {
  13384. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13385. this._cache.rotation.copyFrom(this.rotation);
  13386. }
  13387. // Translation
  13388. if (this.infiniteDistance && !this.parent) {
  13389. var camera = this.getScene().activeCamera;
  13390. if (camera) {
  13391. var cameraWorldMatrix = camera.getWorldMatrix();
  13392. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13393. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13394. }
  13395. }
  13396. else {
  13397. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13398. }
  13399. // Composing transformations
  13400. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13401. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13402. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13403. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13404. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13405. // Need to decompose each rotation here
  13406. var currentPosition = BABYLON.Tmp.Vector3[3];
  13407. if (this.parent && this.parent.getWorldMatrix) {
  13408. if (this._meshToBoneReferal) {
  13409. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13410. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13411. }
  13412. else {
  13413. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13414. }
  13415. }
  13416. else {
  13417. currentPosition.copyFrom(this.position);
  13418. }
  13419. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13420. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13421. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13422. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13423. }
  13424. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13425. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13426. }
  13427. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13428. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13429. }
  13430. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13431. }
  13432. else {
  13433. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13434. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13435. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13436. }
  13437. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13438. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13439. }
  13440. // Local world
  13441. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13442. // Parent
  13443. if (this.parent && this.parent.getWorldMatrix) {
  13444. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13445. if (this._meshToBoneReferal) {
  13446. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13447. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13448. }
  13449. else {
  13450. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13451. }
  13452. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13453. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13454. this._worldMatrix.copyFrom(this._localWorld);
  13455. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13456. }
  13457. else {
  13458. if (this._meshToBoneReferal) {
  13459. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13460. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13461. }
  13462. else {
  13463. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13464. }
  13465. }
  13466. this._markSyncedWithParent();
  13467. }
  13468. else {
  13469. this._worldMatrix.copyFrom(this._localWorld);
  13470. }
  13471. // Bounding info
  13472. this._updateBoundingInfo();
  13473. // Absolute position
  13474. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13475. // Callbacks
  13476. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13477. if (!this._poseMatrix) {
  13478. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13479. }
  13480. return this._worldMatrix;
  13481. };
  13482. /**
  13483. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13484. * @param func: callback function to add
  13485. *
  13486. * Returns the AbstractMesh.
  13487. */
  13488. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13489. this.onAfterWorldMatrixUpdateObservable.add(func);
  13490. return this;
  13491. };
  13492. /**
  13493. * Removes a registered callback function.
  13494. * Returns the AbstractMesh.
  13495. */
  13496. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13497. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13498. return this;
  13499. };
  13500. /**
  13501. * Sets the mesh position in its local space.
  13502. * Returns the AbstractMesh.
  13503. */
  13504. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13505. this.computeWorldMatrix();
  13506. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13507. return this;
  13508. };
  13509. /**
  13510. * Returns the mesh position in the local space from the current World matrix values.
  13511. * Returns a new Vector3.
  13512. */
  13513. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13514. this.computeWorldMatrix();
  13515. var invLocalWorldMatrix = this._localWorld.clone();
  13516. invLocalWorldMatrix.invert();
  13517. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13518. };
  13519. /**
  13520. * Translates the mesh along the passed Vector3 in its local space.
  13521. * Returns the AbstractMesh.
  13522. */
  13523. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13524. this.computeWorldMatrix(true);
  13525. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13526. return this;
  13527. };
  13528. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13529. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13530. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13531. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13532. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13533. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13534. /// <returns>Mesh oriented towards targetMesh</returns>
  13535. if (yawCor === void 0) { yawCor = 0; }
  13536. if (pitchCor === void 0) { pitchCor = 0; }
  13537. if (rollCor === void 0) { rollCor = 0; }
  13538. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13539. var dv = AbstractMesh._lookAtVectorCache;
  13540. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13541. targetPoint.subtractToRef(pos, dv);
  13542. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13543. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13544. var pitch = Math.atan2(dv.y, len);
  13545. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13546. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13547. return this;
  13548. };
  13549. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13550. this._meshToBoneReferal = affectedMesh;
  13551. this.parent = bone;
  13552. if (bone.getWorldMatrix().determinant() < 0) {
  13553. this.scalingDeterminant *= -1;
  13554. }
  13555. return this;
  13556. };
  13557. AbstractMesh.prototype.detachFromBone = function () {
  13558. if (this.parent.getWorldMatrix().determinant() < 0) {
  13559. this.scalingDeterminant *= -1;
  13560. }
  13561. this._meshToBoneReferal = null;
  13562. this.parent = null;
  13563. return this;
  13564. };
  13565. /**
  13566. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13567. * A mesh is in the frustum if its bounding box intersects the frustum.
  13568. * Boolean returned.
  13569. */
  13570. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13571. return this._boundingInfo.isInFrustum(frustumPlanes);
  13572. };
  13573. /**
  13574. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13575. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13576. * Boolean returned.
  13577. */
  13578. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13579. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13580. ;
  13581. };
  13582. /**
  13583. * True if the mesh intersects another mesh or a SolidParticle object.
  13584. * 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)
  13585. * Returns a boolean.
  13586. */
  13587. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13588. if (!this._boundingInfo || !mesh._boundingInfo) {
  13589. return false;
  13590. }
  13591. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13592. };
  13593. /**
  13594. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13595. * Returns a boolean.
  13596. */
  13597. AbstractMesh.prototype.intersectsPoint = function (point) {
  13598. if (!this._boundingInfo) {
  13599. return false;
  13600. }
  13601. return this._boundingInfo.intersectsPoint(point);
  13602. };
  13603. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13604. return this.physicsImpostor;
  13605. };
  13606. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13607. if (!camera) {
  13608. camera = this.getScene().activeCamera;
  13609. }
  13610. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13611. };
  13612. /**
  13613. * Returns the distance from the mesh to the active camera.
  13614. * Returns a float.
  13615. */
  13616. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13617. if (!camera) {
  13618. camera = this.getScene().activeCamera;
  13619. }
  13620. return this.absolutePosition.subtract(camera.position).length();
  13621. };
  13622. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13623. if (!this.physicsImpostor) {
  13624. return;
  13625. }
  13626. this.physicsImpostor.applyImpulse(force, contactPoint);
  13627. return this;
  13628. };
  13629. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13630. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13631. return;
  13632. }
  13633. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13634. mainPivot: pivot1,
  13635. connectedPivot: pivot2,
  13636. nativeParams: options
  13637. });
  13638. return this;
  13639. };
  13640. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13641. // Collisions
  13642. /**
  13643. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13644. * Default `false`.
  13645. */
  13646. get: function () {
  13647. return this._checkCollisions;
  13648. },
  13649. set: function (collisionEnabled) {
  13650. this._checkCollisions = collisionEnabled;
  13651. if (this.getScene().workerCollisions) {
  13652. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13653. }
  13654. },
  13655. enumerable: true,
  13656. configurable: true
  13657. });
  13658. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  13659. var globalPosition = this.getAbsolutePosition();
  13660. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13661. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13662. if (!this._collider) {
  13663. this._collider = new BABYLON.Collider();
  13664. }
  13665. this._collider.radius = this.ellipsoid;
  13666. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13667. return this;
  13668. };
  13669. // Submeshes octree
  13670. /**
  13671. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13672. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13673. * Returns an Octree of submeshes.
  13674. */
  13675. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13676. if (maxCapacity === void 0) { maxCapacity = 64; }
  13677. if (maxDepth === void 0) { maxDepth = 2; }
  13678. if (!this._submeshesOctree) {
  13679. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13680. }
  13681. this.computeWorldMatrix(true);
  13682. // Update octree
  13683. var bbox = this.getBoundingInfo().boundingBox;
  13684. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13685. return this._submeshesOctree;
  13686. };
  13687. // Collisions
  13688. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13689. this._generatePointsArray();
  13690. // Transformation
  13691. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13692. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13693. subMesh._lastColliderWorldVertices = [];
  13694. subMesh._trianglePlanes = [];
  13695. var start = subMesh.verticesStart;
  13696. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13697. for (var i = start; i < end; i++) {
  13698. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13699. }
  13700. }
  13701. // Collide
  13702. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13703. if (collider.collisionFound) {
  13704. collider.collidedMesh = this;
  13705. }
  13706. return this;
  13707. };
  13708. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13709. var subMeshes;
  13710. var len;
  13711. // Octrees
  13712. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13713. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13714. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13715. len = intersections.length;
  13716. subMeshes = intersections.data;
  13717. }
  13718. else {
  13719. subMeshes = this.subMeshes;
  13720. len = subMeshes.length;
  13721. }
  13722. for (var index = 0; index < len; index++) {
  13723. var subMesh = subMeshes[index];
  13724. // Bounding test
  13725. if (len > 1 && !subMesh._checkCollision(collider))
  13726. continue;
  13727. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13728. }
  13729. return this;
  13730. };
  13731. AbstractMesh.prototype._checkCollision = function (collider) {
  13732. // Bounding box test
  13733. if (!this._boundingInfo._checkCollision(collider))
  13734. return this;
  13735. // Transformation matrix
  13736. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13737. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13738. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13739. return this;
  13740. };
  13741. // Picking
  13742. AbstractMesh.prototype._generatePointsArray = function () {
  13743. return false;
  13744. };
  13745. /**
  13746. * Checks if the passed Ray intersects with the mesh.
  13747. * Returns an object PickingInfo.
  13748. */
  13749. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13750. var pickingInfo = new BABYLON.PickingInfo();
  13751. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13752. return pickingInfo;
  13753. }
  13754. if (!this._generatePointsArray()) {
  13755. return pickingInfo;
  13756. }
  13757. var intersectInfo = null;
  13758. // Octrees
  13759. var subMeshes;
  13760. var len;
  13761. if (this._submeshesOctree && this.useOctreeForPicking) {
  13762. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13763. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13764. len = intersections.length;
  13765. subMeshes = intersections.data;
  13766. }
  13767. else {
  13768. subMeshes = this.subMeshes;
  13769. len = subMeshes.length;
  13770. }
  13771. for (var index = 0; index < len; index++) {
  13772. var subMesh = subMeshes[index];
  13773. // Bounding test
  13774. if (len > 1 && !subMesh.canIntersects(ray))
  13775. continue;
  13776. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13777. if (currentIntersectInfo) {
  13778. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13779. intersectInfo = currentIntersectInfo;
  13780. intersectInfo.subMeshId = index;
  13781. if (fastCheck) {
  13782. break;
  13783. }
  13784. }
  13785. }
  13786. }
  13787. if (intersectInfo) {
  13788. // Get picked point
  13789. var world = this.getWorldMatrix();
  13790. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13791. var direction = ray.direction.clone();
  13792. direction = direction.scale(intersectInfo.distance);
  13793. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13794. var pickedPoint = worldOrigin.add(worldDirection);
  13795. // Return result
  13796. pickingInfo.hit = true;
  13797. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13798. pickingInfo.pickedPoint = pickedPoint;
  13799. pickingInfo.pickedMesh = this;
  13800. pickingInfo.bu = intersectInfo.bu;
  13801. pickingInfo.bv = intersectInfo.bv;
  13802. pickingInfo.faceId = intersectInfo.faceId;
  13803. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13804. return pickingInfo;
  13805. }
  13806. return pickingInfo;
  13807. };
  13808. /**
  13809. * Clones the mesh, used by the class Mesh.
  13810. * Just returns `null` for an AbstractMesh.
  13811. */
  13812. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13813. return null;
  13814. };
  13815. /**
  13816. * Disposes all the mesh submeshes.
  13817. * Returns the AbstractMesh.
  13818. */
  13819. AbstractMesh.prototype.releaseSubMeshes = function () {
  13820. if (this.subMeshes) {
  13821. while (this.subMeshes.length) {
  13822. this.subMeshes[0].dispose();
  13823. }
  13824. }
  13825. else {
  13826. this.subMeshes = new Array();
  13827. }
  13828. return this;
  13829. };
  13830. /**
  13831. * Disposes the AbstractMesh.
  13832. * Some internal references are kept for further use.
  13833. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13834. * Returns nothing.
  13835. */
  13836. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13837. var _this = this;
  13838. var index;
  13839. // Action manager
  13840. if (this.actionManager) {
  13841. this.actionManager.dispose();
  13842. this.actionManager = null;
  13843. }
  13844. // Skeleton
  13845. this.skeleton = null;
  13846. // Animations
  13847. this.getScene().stopAnimation(this);
  13848. // Physics
  13849. if (this.physicsImpostor) {
  13850. this.physicsImpostor.dispose();
  13851. }
  13852. // Intersections in progress
  13853. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13854. var other = this._intersectionsInProgress[index];
  13855. var pos = other._intersectionsInProgress.indexOf(this);
  13856. other._intersectionsInProgress.splice(pos, 1);
  13857. }
  13858. this._intersectionsInProgress = [];
  13859. // Lights
  13860. var lights = this.getScene().lights;
  13861. lights.forEach(function (light) {
  13862. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13863. if (meshIndex !== -1) {
  13864. light.includedOnlyMeshes.splice(meshIndex, 1);
  13865. }
  13866. meshIndex = light.excludedMeshes.indexOf(_this);
  13867. if (meshIndex !== -1) {
  13868. light.excludedMeshes.splice(meshIndex, 1);
  13869. }
  13870. // Shadow generators
  13871. var generator = light.getShadowGenerator();
  13872. if (generator) {
  13873. var shadowMap = generator.getShadowMap();
  13874. meshIndex = shadowMap.renderList.indexOf(_this);
  13875. if (meshIndex !== -1) {
  13876. shadowMap.renderList.splice(meshIndex, 1);
  13877. }
  13878. }
  13879. });
  13880. // Edges
  13881. if (this._edgesRenderer) {
  13882. this._edgesRenderer.dispose();
  13883. this._edgesRenderer = null;
  13884. }
  13885. // SubMeshes
  13886. if (this.getClassName() !== "InstancedMesh") {
  13887. this.releaseSubMeshes();
  13888. }
  13889. // Octree
  13890. var sceneOctree = this.getScene().selectionOctree;
  13891. if (sceneOctree) {
  13892. var index = sceneOctree.dynamicContent.indexOf(this);
  13893. if (index !== -1) {
  13894. sceneOctree.dynamicContent.splice(index, 1);
  13895. }
  13896. }
  13897. // Query
  13898. var engine = this.getScene().getEngine();
  13899. if (this._occlusionQuery) {
  13900. this._isOcclusionQueryInProgress = false;
  13901. engine.deleteQuery(this._occlusionQuery);
  13902. this._occlusionQuery = null;
  13903. }
  13904. // Engine
  13905. engine.wipeCaches();
  13906. // Remove from scene
  13907. this.getScene().removeMesh(this);
  13908. if (!doNotRecurse) {
  13909. // Particles
  13910. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13911. if (this.getScene().particleSystems[index].emitter === this) {
  13912. this.getScene().particleSystems[index].dispose();
  13913. index--;
  13914. }
  13915. }
  13916. // Children
  13917. var objects = this.getDescendants(true);
  13918. for (index = 0; index < objects.length; index++) {
  13919. objects[index].dispose();
  13920. }
  13921. }
  13922. else {
  13923. var childMeshes = this.getChildMeshes(true);
  13924. for (index = 0; index < childMeshes.length; index++) {
  13925. var child = childMeshes[index];
  13926. child.parent = null;
  13927. child.computeWorldMatrix(true);
  13928. }
  13929. }
  13930. // facet data
  13931. if (this._facetDataEnabled) {
  13932. this.disableFacetData();
  13933. }
  13934. this.onAfterWorldMatrixUpdateObservable.clear();
  13935. this.onCollideObservable.clear();
  13936. this.onCollisionPositionChangeObservable.clear();
  13937. this._isDisposed = true;
  13938. _super.prototype.dispose.call(this);
  13939. };
  13940. /**
  13941. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13942. * This Vector3 is expressed in the World space.
  13943. */
  13944. AbstractMesh.prototype.getDirection = function (localAxis) {
  13945. var result = BABYLON.Vector3.Zero();
  13946. this.getDirectionToRef(localAxis, result);
  13947. return result;
  13948. };
  13949. /**
  13950. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13951. * localAxis is expressed in the mesh local space.
  13952. * result is computed in the Wordl space from the mesh World matrix.
  13953. * Returns the AbstractMesh.
  13954. */
  13955. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13956. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13957. return this;
  13958. };
  13959. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13960. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13961. if (this.getScene().getRenderId() == 0) {
  13962. this.computeWorldMatrix(true);
  13963. }
  13964. var wm = this.getWorldMatrix();
  13965. if (space == BABYLON.Space.WORLD) {
  13966. var tmat = BABYLON.Tmp.Matrix[0];
  13967. wm.invertToRef(tmat);
  13968. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13969. }
  13970. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13971. this._pivotMatrix.m[12] = -point.x;
  13972. this._pivotMatrix.m[13] = -point.y;
  13973. this._pivotMatrix.m[14] = -point.z;
  13974. this._cache.pivotMatrixUpdated = true;
  13975. return this;
  13976. };
  13977. /**
  13978. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13979. */
  13980. AbstractMesh.prototype.getPivotPoint = function () {
  13981. var point = BABYLON.Vector3.Zero();
  13982. this.getPivotPointToRef(point);
  13983. return point;
  13984. };
  13985. /**
  13986. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13987. * Returns the AbstractMesh.
  13988. */
  13989. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13990. result.x = -this._pivotMatrix.m[12];
  13991. result.y = -this._pivotMatrix.m[13];
  13992. result.z = -this._pivotMatrix.m[14];
  13993. return this;
  13994. };
  13995. /**
  13996. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13997. */
  13998. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13999. var point = BABYLON.Vector3.Zero();
  14000. this.getAbsolutePivotPointToRef(point);
  14001. return point;
  14002. };
  14003. /**
  14004. * Defines the passed mesh as the parent of the current mesh.
  14005. * Returns the AbstractMesh.
  14006. */
  14007. AbstractMesh.prototype.setParent = function (mesh) {
  14008. var child = this;
  14009. var parent = mesh;
  14010. if (mesh == null) {
  14011. var rotation = BABYLON.Tmp.Quaternion[0];
  14012. var position = BABYLON.Tmp.Vector3[0];
  14013. var scale = BABYLON.Tmp.Vector3[1];
  14014. child.getWorldMatrix().decompose(scale, rotation, position);
  14015. if (child.rotationQuaternion) {
  14016. child.rotationQuaternion.copyFrom(rotation);
  14017. }
  14018. else {
  14019. rotation.toEulerAnglesToRef(child.rotation);
  14020. }
  14021. child.position.x = position.x;
  14022. child.position.y = position.y;
  14023. child.position.z = position.z;
  14024. }
  14025. else {
  14026. var position = BABYLON.Tmp.Vector3[0];
  14027. var m1 = BABYLON.Tmp.Matrix[0];
  14028. parent.getWorldMatrix().invertToRef(m1);
  14029. BABYLON.Vector3.TransformCoordinatesToRef(child.position, m1, position);
  14030. child.position.copyFrom(position);
  14031. }
  14032. child.parent = parent;
  14033. return this;
  14034. };
  14035. /**
  14036. * Adds the passed mesh as a child to the current mesh.
  14037. * Returns the AbstractMesh.
  14038. */
  14039. AbstractMesh.prototype.addChild = function (mesh) {
  14040. mesh.setParent(this);
  14041. return this;
  14042. };
  14043. /**
  14044. * Removes the passed mesh from the current mesh children list.
  14045. * Returns the AbstractMesh.
  14046. */
  14047. AbstractMesh.prototype.removeChild = function (mesh) {
  14048. mesh.setParent(null);
  14049. return this;
  14050. };
  14051. /**
  14052. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14053. * Returns the AbstractMesh.
  14054. */
  14055. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14056. result.x = this._pivotMatrix.m[12];
  14057. result.y = this._pivotMatrix.m[13];
  14058. result.z = this._pivotMatrix.m[14];
  14059. this.getPivotPointToRef(result);
  14060. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14061. return this;
  14062. };
  14063. // Facet data
  14064. /**
  14065. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14066. * Returns the AbstractMesh.
  14067. */
  14068. AbstractMesh.prototype._initFacetData = function () {
  14069. if (!this._facetNormals) {
  14070. this._facetNormals = new Array();
  14071. }
  14072. if (!this._facetPositions) {
  14073. this._facetPositions = new Array();
  14074. }
  14075. if (!this._facetPartitioning) {
  14076. this._facetPartitioning = new Array();
  14077. }
  14078. this._facetNb = this.getIndices().length / 3;
  14079. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14080. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14081. for (var f = 0; f < this._facetNb; f++) {
  14082. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14083. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14084. }
  14085. this._facetDataEnabled = true;
  14086. return this;
  14087. };
  14088. /**
  14089. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14090. * This method can be called within the render loop.
  14091. * 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.
  14092. * Returns the AbstractMesh.
  14093. */
  14094. AbstractMesh.prototype.updateFacetData = function () {
  14095. if (!this._facetDataEnabled) {
  14096. this._initFacetData();
  14097. }
  14098. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14099. var indices = this.getIndices();
  14100. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14101. var bInfo = this.getBoundingInfo();
  14102. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14103. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14104. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14105. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14106. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14107. this._subDiv.max = this._partitioningSubdivisions;
  14108. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14109. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14110. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14111. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14112. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14113. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14114. // set the parameters for ComputeNormals()
  14115. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14116. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14117. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14118. this._facetParameters.bInfo = bInfo;
  14119. this._facetParameters.bbSize = this._bbSize;
  14120. this._facetParameters.subDiv = this._subDiv;
  14121. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14122. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14123. return this;
  14124. };
  14125. /**
  14126. * Returns the facetLocalNormals array.
  14127. * The normals are expressed in the mesh local space.
  14128. */
  14129. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14130. if (!this._facetNormals) {
  14131. this.updateFacetData();
  14132. }
  14133. return this._facetNormals;
  14134. };
  14135. /**
  14136. * Returns the facetLocalPositions array.
  14137. * The facet positions are expressed in the mesh local space.
  14138. */
  14139. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14140. if (!this._facetPositions) {
  14141. this.updateFacetData();
  14142. }
  14143. return this._facetPositions;
  14144. };
  14145. /**
  14146. * Returns the facetLocalPartioning array.
  14147. */
  14148. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14149. if (!this._facetPartitioning) {
  14150. this.updateFacetData();
  14151. }
  14152. return this._facetPartitioning;
  14153. };
  14154. /**
  14155. * Returns the i-th facet position in the world system.
  14156. * This method allocates a new Vector3 per call.
  14157. */
  14158. AbstractMesh.prototype.getFacetPosition = function (i) {
  14159. var pos = BABYLON.Vector3.Zero();
  14160. this.getFacetPositionToRef(i, pos);
  14161. return pos;
  14162. };
  14163. /**
  14164. * Sets the reference Vector3 with the i-th facet position in the world system.
  14165. * Returns the AbstractMesh.
  14166. */
  14167. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14168. var localPos = (this.getFacetLocalPositions())[i];
  14169. var world = this.getWorldMatrix();
  14170. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14171. return this;
  14172. };
  14173. /**
  14174. * Returns the i-th facet normal in the world system.
  14175. * This method allocates a new Vector3 per call.
  14176. */
  14177. AbstractMesh.prototype.getFacetNormal = function (i) {
  14178. var norm = BABYLON.Vector3.Zero();
  14179. this.getFacetNormalToRef(i, norm);
  14180. return norm;
  14181. };
  14182. /**
  14183. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14184. * Returns the AbstractMesh.
  14185. */
  14186. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14187. var localNorm = (this.getFacetLocalNormals())[i];
  14188. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14189. return this;
  14190. };
  14191. /**
  14192. * 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).
  14193. */
  14194. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14195. var bInfo = this.getBoundingInfo();
  14196. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14197. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14198. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14199. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14200. return null;
  14201. }
  14202. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14203. };
  14204. /**
  14205. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14206. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14207. * 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.
  14208. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14209. * 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.
  14210. */
  14211. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14212. if (checkFace === void 0) { checkFace = false; }
  14213. if (facing === void 0) { facing = true; }
  14214. var world = this.getWorldMatrix();
  14215. var invMat = BABYLON.Tmp.Matrix[5];
  14216. world.invertToRef(invMat);
  14217. var invVect = BABYLON.Tmp.Vector3[8];
  14218. var closest = null;
  14219. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14220. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14221. if (projected) {
  14222. // tranform the local computed projected vector to world coordinates
  14223. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14224. }
  14225. return closest;
  14226. };
  14227. /**
  14228. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14229. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14230. * 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.
  14231. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14232. * 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.
  14233. */
  14234. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14235. if (checkFace === void 0) { checkFace = false; }
  14236. if (facing === void 0) { facing = true; }
  14237. var closest = null;
  14238. var tmpx = 0.0;
  14239. var tmpy = 0.0;
  14240. var tmpz = 0.0;
  14241. var d = 0.0; // tmp dot facet normal * facet position
  14242. var t0 = 0.0;
  14243. var projx = 0.0;
  14244. var projy = 0.0;
  14245. var projz = 0.0;
  14246. // Get all the facets in the same partitioning block than (x, y, z)
  14247. var facetPositions = this.getFacetLocalPositions();
  14248. var facetNormals = this.getFacetLocalNormals();
  14249. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14250. if (!facetsInBlock) {
  14251. return null;
  14252. }
  14253. // Get the closest facet to (x, y, z)
  14254. var shortest = Number.MAX_VALUE; // init distance vars
  14255. var tmpDistance = shortest;
  14256. var fib; // current facet in the block
  14257. var norm; // current facet normal
  14258. var p0; // current facet barycenter position
  14259. // loop on all the facets in the current partitioning block
  14260. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14261. fib = facetsInBlock[idx];
  14262. norm = facetNormals[fib];
  14263. p0 = facetPositions[fib];
  14264. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14265. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14266. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14267. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14268. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14269. projx = x + norm.x * t0;
  14270. projy = y + norm.y * t0;
  14271. projz = z + norm.z * t0;
  14272. tmpx = projx - x;
  14273. tmpy = projy - y;
  14274. tmpz = projz - z;
  14275. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14276. if (tmpDistance < shortest) {
  14277. shortest = tmpDistance;
  14278. closest = fib;
  14279. if (projected) {
  14280. projected.x = projx;
  14281. projected.y = projy;
  14282. projected.z = projz;
  14283. }
  14284. }
  14285. }
  14286. }
  14287. return closest;
  14288. };
  14289. /**
  14290. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14291. */
  14292. AbstractMesh.prototype.getFacetDataParameters = function () {
  14293. return this._facetParameters;
  14294. };
  14295. /**
  14296. * Disables the feature FacetData and frees the related memory.
  14297. * Returns the AbstractMesh.
  14298. */
  14299. AbstractMesh.prototype.disableFacetData = function () {
  14300. if (this._facetDataEnabled) {
  14301. this._facetDataEnabled = false;
  14302. this._facetPositions = null;
  14303. this._facetNormals = null;
  14304. this._facetPartitioning = null;
  14305. this._facetParameters = null;
  14306. }
  14307. return this;
  14308. };
  14309. /**
  14310. * Creates new normals data for the mesh.
  14311. * @param updatable.
  14312. */
  14313. AbstractMesh.prototype.createNormals = function (updatable) {
  14314. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14315. var indices = this.getIndices();
  14316. var normals;
  14317. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14318. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14319. }
  14320. else {
  14321. normals = [];
  14322. }
  14323. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14324. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14325. };
  14326. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14327. var engine = this.getEngine();
  14328. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14329. this._isOccluded = false;
  14330. return;
  14331. }
  14332. if (this.isOcclusionQueryInProgress) {
  14333. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14334. if (isOcclusionQueryAvailable) {
  14335. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14336. this._isOcclusionQueryInProgress = false;
  14337. this._occlusionInternalRetryCounter = 0;
  14338. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14339. }
  14340. else {
  14341. this._occlusionInternalRetryCounter++;
  14342. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14343. this._isOcclusionQueryInProgress = false;
  14344. this._occlusionInternalRetryCounter = 0;
  14345. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14346. // if strict continue the last state of the object.
  14347. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14348. }
  14349. else {
  14350. return;
  14351. }
  14352. }
  14353. }
  14354. var scene = this.getScene();
  14355. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14356. if (!this._occlusionQuery) {
  14357. this._occlusionQuery = engine.createQuery();
  14358. }
  14359. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14360. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14361. engine.endQuery(this.occlusionQueryAlgorithmType);
  14362. this._isOcclusionQueryInProgress = true;
  14363. };
  14364. return AbstractMesh;
  14365. }(BABYLON.Node));
  14366. // Statics
  14367. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14368. AbstractMesh._BILLBOARDMODE_X = 1;
  14369. AbstractMesh._BILLBOARDMODE_Y = 2;
  14370. AbstractMesh._BILLBOARDMODE_Z = 4;
  14371. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14372. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14373. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14374. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14375. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14376. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14377. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14378. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14379. BABYLON.AbstractMesh = AbstractMesh;
  14380. })(BABYLON || (BABYLON = {}));
  14381. //# sourceMappingURL=babylon.abstractMesh.js.map
  14382. var BABYLON;
  14383. (function (BABYLON) {
  14384. var Light = (function (_super) {
  14385. __extends(Light, _super);
  14386. /**
  14387. * Creates a Light object in the scene.
  14388. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14389. */
  14390. function Light(name, scene) {
  14391. var _this = _super.call(this, name, scene) || this;
  14392. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14393. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14394. _this.intensity = 1.0;
  14395. _this.range = Number.MAX_VALUE;
  14396. /**
  14397. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14398. * of light.
  14399. */
  14400. _this._photometricScale = 1.0;
  14401. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14402. _this._radius = 0.00001;
  14403. _this.renderPriority = 0;
  14404. /**
  14405. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14406. * the current shadow generator.
  14407. */
  14408. _this.shadowEnabled = true;
  14409. _this._excludeWithLayerMask = 0;
  14410. _this._includeOnlyWithLayerMask = 0;
  14411. _this._lightmapMode = 0;
  14412. _this._excludedMeshesIds = new Array();
  14413. _this._includedOnlyMeshesIds = new Array();
  14414. _this.getScene().addLight(_this);
  14415. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14416. _this._buildUniformLayout();
  14417. _this.includedOnlyMeshes = new Array();
  14418. _this.excludedMeshes = new Array();
  14419. _this._resyncMeshes();
  14420. return _this;
  14421. }
  14422. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14423. /**
  14424. * If every light affecting the material is in this lightmapMode,
  14425. * material.lightmapTexture adds or multiplies
  14426. * (depends on material.useLightmapAsShadowmap)
  14427. * after every other light calculations.
  14428. */
  14429. get: function () {
  14430. return Light._LIGHTMAP_DEFAULT;
  14431. },
  14432. enumerable: true,
  14433. configurable: true
  14434. });
  14435. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14436. /**
  14437. * material.lightmapTexture as only diffuse lighting from this light
  14438. * adds pnly specular lighting from this light
  14439. * adds dynamic shadows
  14440. */
  14441. get: function () {
  14442. return Light._LIGHTMAP_SPECULAR;
  14443. },
  14444. enumerable: true,
  14445. configurable: true
  14446. });
  14447. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14448. /**
  14449. * material.lightmapTexture as only lighting
  14450. * no light calculation from this light
  14451. * only adds dynamic shadows from this light
  14452. */
  14453. get: function () {
  14454. return Light._LIGHTMAP_SHADOWSONLY;
  14455. },
  14456. enumerable: true,
  14457. configurable: true
  14458. });
  14459. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14460. /**
  14461. * Each light type uses the default quantity according to its type:
  14462. * point/spot lights use luminous intensity
  14463. * directional lights use illuminance
  14464. */
  14465. get: function () {
  14466. return Light._INTENSITYMODE_AUTOMATIC;
  14467. },
  14468. enumerable: true,
  14469. configurable: true
  14470. });
  14471. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14472. /**
  14473. * lumen (lm)
  14474. */
  14475. get: function () {
  14476. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14477. },
  14478. enumerable: true,
  14479. configurable: true
  14480. });
  14481. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14482. /**
  14483. * candela (lm/sr)
  14484. */
  14485. get: function () {
  14486. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14487. },
  14488. enumerable: true,
  14489. configurable: true
  14490. });
  14491. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14492. /**
  14493. * lux (lm/m^2)
  14494. */
  14495. get: function () {
  14496. return Light._INTENSITYMODE_ILLUMINANCE;
  14497. },
  14498. enumerable: true,
  14499. configurable: true
  14500. });
  14501. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14502. /**
  14503. * nit (cd/m^2)
  14504. */
  14505. get: function () {
  14506. return Light._INTENSITYMODE_LUMINANCE;
  14507. },
  14508. enumerable: true,
  14509. configurable: true
  14510. });
  14511. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14512. /**
  14513. * Light type const id of the point light.
  14514. */
  14515. get: function () {
  14516. return Light._LIGHTTYPEID_POINTLIGHT;
  14517. },
  14518. enumerable: true,
  14519. configurable: true
  14520. });
  14521. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14522. /**
  14523. * Light type const id of the directional light.
  14524. */
  14525. get: function () {
  14526. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14527. },
  14528. enumerable: true,
  14529. configurable: true
  14530. });
  14531. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14532. /**
  14533. * Light type const id of the spot light.
  14534. */
  14535. get: function () {
  14536. return Light._LIGHTTYPEID_SPOTLIGHT;
  14537. },
  14538. enumerable: true,
  14539. configurable: true
  14540. });
  14541. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14542. /**
  14543. * Light type const id of the hemispheric light.
  14544. */
  14545. get: function () {
  14546. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14547. },
  14548. enumerable: true,
  14549. configurable: true
  14550. });
  14551. Object.defineProperty(Light.prototype, "intensityMode", {
  14552. /**
  14553. * Gets the photometric scale used to interpret the intensity.
  14554. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14555. */
  14556. get: function () {
  14557. return this._intensityMode;
  14558. },
  14559. /**
  14560. * Sets the photometric scale used to interpret the intensity.
  14561. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14562. */
  14563. set: function (value) {
  14564. this._intensityMode = value;
  14565. this._computePhotometricScale();
  14566. },
  14567. enumerable: true,
  14568. configurable: true
  14569. });
  14570. ;
  14571. ;
  14572. Object.defineProperty(Light.prototype, "radius", {
  14573. /**
  14574. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14575. */
  14576. get: function () {
  14577. return this._radius;
  14578. },
  14579. /**
  14580. * sets the light radius used by PBR Materials to simulate soft area lights.
  14581. */
  14582. set: function (value) {
  14583. this._radius = value;
  14584. this._computePhotometricScale();
  14585. },
  14586. enumerable: true,
  14587. configurable: true
  14588. });
  14589. ;
  14590. ;
  14591. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14592. get: function () {
  14593. return this._includedOnlyMeshes;
  14594. },
  14595. set: function (value) {
  14596. this._includedOnlyMeshes = value;
  14597. this._hookArrayForIncludedOnly(value);
  14598. },
  14599. enumerable: true,
  14600. configurable: true
  14601. });
  14602. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14603. get: function () {
  14604. return this._excludedMeshes;
  14605. },
  14606. set: function (value) {
  14607. this._excludedMeshes = value;
  14608. this._hookArrayForExcluded(value);
  14609. },
  14610. enumerable: true,
  14611. configurable: true
  14612. });
  14613. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14614. get: function () {
  14615. return this._excludeWithLayerMask;
  14616. },
  14617. set: function (value) {
  14618. this._excludeWithLayerMask = value;
  14619. this._resyncMeshes();
  14620. },
  14621. enumerable: true,
  14622. configurable: true
  14623. });
  14624. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14625. get: function () {
  14626. return this._includeOnlyWithLayerMask;
  14627. },
  14628. set: function (value) {
  14629. this._includeOnlyWithLayerMask = value;
  14630. this._resyncMeshes();
  14631. },
  14632. enumerable: true,
  14633. configurable: true
  14634. });
  14635. Object.defineProperty(Light.prototype, "lightmapMode", {
  14636. get: function () {
  14637. return this._lightmapMode;
  14638. },
  14639. set: function (value) {
  14640. if (this._lightmapMode === value) {
  14641. return;
  14642. }
  14643. this._lightmapMode = value;
  14644. this._markMeshesAsLightDirty();
  14645. },
  14646. enumerable: true,
  14647. configurable: true
  14648. });
  14649. Light.prototype._buildUniformLayout = function () {
  14650. // Overridden
  14651. };
  14652. /**
  14653. * Returns the string "Light".
  14654. */
  14655. Light.prototype.getClassName = function () {
  14656. return "Light";
  14657. };
  14658. /**
  14659. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14660. */
  14661. Light.prototype.toString = function (fullDetails) {
  14662. var ret = "Name: " + this.name;
  14663. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14664. if (this.animations) {
  14665. for (var i = 0; i < this.animations.length; i++) {
  14666. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14667. }
  14668. }
  14669. if (fullDetails) {
  14670. }
  14671. return ret;
  14672. };
  14673. /**
  14674. * Set the enabled state of this node.
  14675. * @param {boolean} value - the new enabled state
  14676. * @see isEnabled
  14677. */
  14678. Light.prototype.setEnabled = function (value) {
  14679. _super.prototype.setEnabled.call(this, value);
  14680. this._resyncMeshes();
  14681. };
  14682. /**
  14683. * Returns the Light associated shadow generator.
  14684. */
  14685. Light.prototype.getShadowGenerator = function () {
  14686. return this._shadowGenerator;
  14687. };
  14688. /**
  14689. * Returns a Vector3, the absolute light position in the World.
  14690. */
  14691. Light.prototype.getAbsolutePosition = function () {
  14692. return BABYLON.Vector3.Zero();
  14693. };
  14694. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14695. };
  14696. Light.prototype._getWorldMatrix = function () {
  14697. return BABYLON.Matrix.Identity();
  14698. };
  14699. /**
  14700. * Boolean : True if the light will affect the passed mesh.
  14701. */
  14702. Light.prototype.canAffectMesh = function (mesh) {
  14703. if (!mesh) {
  14704. return true;
  14705. }
  14706. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14707. return false;
  14708. }
  14709. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14710. return false;
  14711. }
  14712. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14713. return false;
  14714. }
  14715. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14716. return false;
  14717. }
  14718. return true;
  14719. };
  14720. /**
  14721. * Returns the light World matrix.
  14722. */
  14723. Light.prototype.getWorldMatrix = function () {
  14724. this._currentRenderId = this.getScene().getRenderId();
  14725. var worldMatrix = this._getWorldMatrix();
  14726. if (this.parent && this.parent.getWorldMatrix) {
  14727. if (!this._parentedWorldMatrix) {
  14728. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14729. }
  14730. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14731. this._markSyncedWithParent();
  14732. return this._parentedWorldMatrix;
  14733. }
  14734. return worldMatrix;
  14735. };
  14736. /**
  14737. * Sort function to order lights for rendering.
  14738. * @param a First Light object to compare to second.
  14739. * @param b Second Light object to compare first.
  14740. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14741. */
  14742. Light.compareLightsPriority = function (a, b) {
  14743. //shadow-casting lights have priority over non-shadow-casting lights
  14744. //the renderPrioirty is a secondary sort criterion
  14745. if (a.shadowEnabled !== b.shadowEnabled) {
  14746. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14747. }
  14748. return b.renderPriority - a.renderPriority;
  14749. };
  14750. /**
  14751. * Disposes the light.
  14752. */
  14753. Light.prototype.dispose = function () {
  14754. if (this._shadowGenerator) {
  14755. this._shadowGenerator.dispose();
  14756. this._shadowGenerator = null;
  14757. }
  14758. // Animations
  14759. this.getScene().stopAnimation(this);
  14760. // Remove from meshes
  14761. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14762. var mesh = _a[_i];
  14763. mesh._removeLightSource(this);
  14764. }
  14765. this._uniformBuffer.dispose();
  14766. // Remove from scene
  14767. this.getScene().removeLight(this);
  14768. _super.prototype.dispose.call(this);
  14769. };
  14770. /**
  14771. * Returns the light type ID (integer).
  14772. */
  14773. Light.prototype.getTypeID = function () {
  14774. return 0;
  14775. };
  14776. /**
  14777. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14778. */
  14779. Light.prototype.getScaledIntensity = function () {
  14780. return this._photometricScale * this.intensity;
  14781. };
  14782. /**
  14783. * Returns a new Light object, named "name", from the current one.
  14784. */
  14785. Light.prototype.clone = function (name) {
  14786. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14787. };
  14788. /**
  14789. * Serializes the current light into a Serialization object.
  14790. * Returns the serialized object.
  14791. */
  14792. Light.prototype.serialize = function () {
  14793. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14794. // Type
  14795. serializationObject.type = this.getTypeID();
  14796. // Parent
  14797. if (this.parent) {
  14798. serializationObject.parentId = this.parent.id;
  14799. }
  14800. // Inclusion / exclusions
  14801. if (this.excludedMeshes.length > 0) {
  14802. serializationObject.excludedMeshesIds = [];
  14803. this.excludedMeshes.forEach(function (mesh) {
  14804. serializationObject.excludedMeshesIds.push(mesh.id);
  14805. });
  14806. }
  14807. if (this.includedOnlyMeshes.length > 0) {
  14808. serializationObject.includedOnlyMeshesIds = [];
  14809. this.includedOnlyMeshes.forEach(function (mesh) {
  14810. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14811. });
  14812. }
  14813. // Animations
  14814. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14815. serializationObject.ranges = this.serializeAnimationRanges();
  14816. return serializationObject;
  14817. };
  14818. /**
  14819. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14820. * This new light is named "name" and added to the passed scene.
  14821. */
  14822. Light.GetConstructorFromName = function (type, name, scene) {
  14823. switch (type) {
  14824. case 0:
  14825. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14826. case 1:
  14827. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14828. case 2:
  14829. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14830. case 3:
  14831. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14832. }
  14833. };
  14834. /**
  14835. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14836. */
  14837. Light.Parse = function (parsedLight, scene) {
  14838. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14839. // Inclusion / exclusions
  14840. if (parsedLight.excludedMeshesIds) {
  14841. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14842. }
  14843. if (parsedLight.includedOnlyMeshesIds) {
  14844. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14845. }
  14846. // Parent
  14847. if (parsedLight.parentId) {
  14848. light._waitingParentId = parsedLight.parentId;
  14849. }
  14850. // Animations
  14851. if (parsedLight.animations) {
  14852. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14853. var parsedAnimation = parsedLight.animations[animationIndex];
  14854. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14855. }
  14856. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14857. }
  14858. if (parsedLight.autoAnimate) {
  14859. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14860. }
  14861. return light;
  14862. };
  14863. Light.prototype._hookArrayForExcluded = function (array) {
  14864. var _this = this;
  14865. var oldPush = array.push;
  14866. array.push = function () {
  14867. var items = [];
  14868. for (var _i = 0; _i < arguments.length; _i++) {
  14869. items[_i] = arguments[_i];
  14870. }
  14871. var result = oldPush.apply(array, items);
  14872. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14873. var item = items_1[_a];
  14874. item._resyncLighSource(_this);
  14875. }
  14876. return result;
  14877. };
  14878. var oldSplice = array.splice;
  14879. array.splice = function (index, deleteCount) {
  14880. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14881. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14882. var item = deleted_1[_i];
  14883. item._resyncLighSource(_this);
  14884. }
  14885. return deleted;
  14886. };
  14887. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14888. var item = array_1[_i];
  14889. item._resyncLighSource(this);
  14890. }
  14891. };
  14892. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14893. var _this = this;
  14894. var oldPush = array.push;
  14895. array.push = function () {
  14896. var items = [];
  14897. for (var _i = 0; _i < arguments.length; _i++) {
  14898. items[_i] = arguments[_i];
  14899. }
  14900. var result = oldPush.apply(array, items);
  14901. _this._resyncMeshes();
  14902. return result;
  14903. };
  14904. var oldSplice = array.splice;
  14905. array.splice = function (index, deleteCount) {
  14906. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14907. _this._resyncMeshes();
  14908. return deleted;
  14909. };
  14910. this._resyncMeshes();
  14911. };
  14912. Light.prototype._resyncMeshes = function () {
  14913. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14914. var mesh = _a[_i];
  14915. mesh._resyncLighSource(this);
  14916. }
  14917. };
  14918. Light.prototype._markMeshesAsLightDirty = function () {
  14919. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14920. var mesh = _a[_i];
  14921. if (mesh._lightSources.indexOf(this) !== -1) {
  14922. mesh._markSubMeshesAsLightDirty();
  14923. }
  14924. }
  14925. };
  14926. /**
  14927. * Recomputes the cached photometric scale if needed.
  14928. */
  14929. Light.prototype._computePhotometricScale = function () {
  14930. this._photometricScale = this._getPhotometricScale();
  14931. this.getScene().resetCachedMaterial();
  14932. };
  14933. /**
  14934. * Returns the Photometric Scale according to the light type and intensity mode.
  14935. */
  14936. Light.prototype._getPhotometricScale = function () {
  14937. var photometricScale = 0.0;
  14938. var lightTypeID = this.getTypeID();
  14939. //get photometric mode
  14940. var photometricMode = this.intensityMode;
  14941. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14942. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14943. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14944. }
  14945. else {
  14946. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14947. }
  14948. }
  14949. //compute photometric scale
  14950. switch (lightTypeID) {
  14951. case Light.LIGHTTYPEID_POINTLIGHT:
  14952. case Light.LIGHTTYPEID_SPOTLIGHT:
  14953. switch (photometricMode) {
  14954. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14955. photometricScale = 1.0 / (4.0 * Math.PI);
  14956. break;
  14957. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14958. photometricScale = 1.0;
  14959. break;
  14960. case Light.INTENSITYMODE_LUMINANCE:
  14961. photometricScale = this.radius * this.radius;
  14962. break;
  14963. }
  14964. break;
  14965. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14966. switch (photometricMode) {
  14967. case Light.INTENSITYMODE_ILLUMINANCE:
  14968. photometricScale = 1.0;
  14969. break;
  14970. case Light.INTENSITYMODE_LUMINANCE:
  14971. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14972. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14973. var apexAngleRadians = this.radius;
  14974. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14975. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14976. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14977. photometricScale = solidAngle;
  14978. break;
  14979. }
  14980. break;
  14981. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14982. // No fall off in hemisperic light.
  14983. photometricScale = 1.0;
  14984. break;
  14985. }
  14986. return photometricScale;
  14987. };
  14988. Light.prototype._reorderLightsInScene = function () {
  14989. var scene = this.getScene();
  14990. if (this.renderPriority != 0) {
  14991. scene.requireLightSorting = true;
  14992. }
  14993. this.getScene().sortLightsByPriority();
  14994. };
  14995. return Light;
  14996. }(BABYLON.Node));
  14997. //lightmapMode Consts
  14998. Light._LIGHTMAP_DEFAULT = 0;
  14999. Light._LIGHTMAP_SPECULAR = 1;
  15000. Light._LIGHTMAP_SHADOWSONLY = 2;
  15001. // Intensity Mode Consts
  15002. Light._INTENSITYMODE_AUTOMATIC = 0;
  15003. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15004. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15005. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15006. Light._INTENSITYMODE_LUMINANCE = 4;
  15007. // Light types ids const.
  15008. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15009. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15010. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15011. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15012. __decorate([
  15013. BABYLON.serializeAsColor3()
  15014. ], Light.prototype, "diffuse", void 0);
  15015. __decorate([
  15016. BABYLON.serializeAsColor3()
  15017. ], Light.prototype, "specular", void 0);
  15018. __decorate([
  15019. BABYLON.serialize()
  15020. ], Light.prototype, "intensity", void 0);
  15021. __decorate([
  15022. BABYLON.serialize()
  15023. ], Light.prototype, "range", void 0);
  15024. __decorate([
  15025. BABYLON.serialize()
  15026. ], Light.prototype, "intensityMode", null);
  15027. __decorate([
  15028. BABYLON.serialize()
  15029. ], Light.prototype, "radius", null);
  15030. __decorate([
  15031. BABYLON.serialize()
  15032. ], Light.prototype, "_renderPriority", void 0);
  15033. __decorate([
  15034. BABYLON.expandToProperty("_reorderLightsInScene")
  15035. ], Light.prototype, "renderPriority", void 0);
  15036. __decorate([
  15037. BABYLON.serialize()
  15038. ], Light.prototype, "shadowEnabled", void 0);
  15039. __decorate([
  15040. BABYLON.serialize("excludeWithLayerMask")
  15041. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15042. __decorate([
  15043. BABYLON.serialize("includeOnlyWithLayerMask")
  15044. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15045. __decorate([
  15046. BABYLON.serialize("lightmapMode")
  15047. ], Light.prototype, "_lightmapMode", void 0);
  15048. BABYLON.Light = Light;
  15049. })(BABYLON || (BABYLON = {}));
  15050. //# sourceMappingURL=babylon.light.js.map
  15051. var BABYLON;
  15052. (function (BABYLON) {
  15053. var Camera = (function (_super) {
  15054. __extends(Camera, _super);
  15055. function Camera(name, position, scene) {
  15056. var _this = _super.call(this, name, scene) || this;
  15057. _this.upVector = BABYLON.Vector3.Up();
  15058. _this.orthoLeft = null;
  15059. _this.orthoRight = null;
  15060. _this.orthoBottom = null;
  15061. _this.orthoTop = null;
  15062. _this.fov = 0.8;
  15063. _this.minZ = 1;
  15064. _this.maxZ = 10000.0;
  15065. _this.inertia = 0.9;
  15066. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15067. _this.isIntermediate = false;
  15068. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15069. _this.layerMask = 0x0FFFFFFF;
  15070. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15071. // Camera rig members
  15072. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15073. _this._rigCameras = new Array();
  15074. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15075. _this._skipRendering = false;
  15076. _this.customRenderTargets = new Array();
  15077. // Observables
  15078. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15079. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15080. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15081. _this.onRestoreStateObservable = new BABYLON.Observable();
  15082. // Cache
  15083. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15084. _this._projectionMatrix = new BABYLON.Matrix();
  15085. _this._doNotComputeProjectionMatrix = false;
  15086. _this._postProcesses = new Array();
  15087. _this._transformMatrix = BABYLON.Matrix.Zero();
  15088. _this._activeMeshes = new BABYLON.SmartArray(256);
  15089. _this._globalPosition = BABYLON.Vector3.Zero();
  15090. _this._refreshFrustumPlanes = true;
  15091. _this.getScene().addCamera(_this);
  15092. if (!_this.getScene().activeCamera) {
  15093. _this.getScene().activeCamera = _this;
  15094. }
  15095. _this.position = position;
  15096. return _this;
  15097. }
  15098. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15099. get: function () {
  15100. return Camera._PERSPECTIVE_CAMERA;
  15101. },
  15102. enumerable: true,
  15103. configurable: true
  15104. });
  15105. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15106. get: function () {
  15107. return Camera._ORTHOGRAPHIC_CAMERA;
  15108. },
  15109. enumerable: true,
  15110. configurable: true
  15111. });
  15112. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15113. get: function () {
  15114. return Camera._FOVMODE_VERTICAL_FIXED;
  15115. },
  15116. enumerable: true,
  15117. configurable: true
  15118. });
  15119. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15120. get: function () {
  15121. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15122. },
  15123. enumerable: true,
  15124. configurable: true
  15125. });
  15126. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15127. get: function () {
  15128. return Camera._RIG_MODE_NONE;
  15129. },
  15130. enumerable: true,
  15131. configurable: true
  15132. });
  15133. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15134. get: function () {
  15135. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15136. },
  15137. enumerable: true,
  15138. configurable: true
  15139. });
  15140. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15141. get: function () {
  15142. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15143. },
  15144. enumerable: true,
  15145. configurable: true
  15146. });
  15147. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15148. get: function () {
  15149. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15150. },
  15151. enumerable: true,
  15152. configurable: true
  15153. });
  15154. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15155. get: function () {
  15156. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15157. },
  15158. enumerable: true,
  15159. configurable: true
  15160. });
  15161. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15162. get: function () {
  15163. return Camera._RIG_MODE_VR;
  15164. },
  15165. enumerable: true,
  15166. configurable: true
  15167. });
  15168. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15169. get: function () {
  15170. return Camera._RIG_MODE_WEBVR;
  15171. },
  15172. enumerable: true,
  15173. configurable: true
  15174. });
  15175. /**
  15176. * Store current camera state (fov, position, etc..)
  15177. */
  15178. Camera.prototype.storeState = function () {
  15179. this._stateStored = true;
  15180. this._storedFov = this.fov;
  15181. return this;
  15182. };
  15183. /**
  15184. * Restores the camera state values if it has been stored. You must call storeState() first
  15185. */
  15186. Camera.prototype._restoreStateValues = function () {
  15187. if (!this._stateStored) {
  15188. return false;
  15189. }
  15190. this.fov = this._storedFov;
  15191. return true;
  15192. };
  15193. /**
  15194. * Restored camera state. You must call storeState() first
  15195. */
  15196. Camera.prototype.restoreState = function () {
  15197. if (this._restoreStateValues()) {
  15198. this.onRestoreStateObservable.notifyObservers(this);
  15199. return true;
  15200. }
  15201. return false;
  15202. };
  15203. Camera.prototype.getClassName = function () {
  15204. return "Camera";
  15205. };
  15206. /**
  15207. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15208. */
  15209. Camera.prototype.toString = function (fullDetails) {
  15210. var ret = "Name: " + this.name;
  15211. ret += ", type: " + this.getClassName();
  15212. if (this.animations) {
  15213. for (var i = 0; i < this.animations.length; i++) {
  15214. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15215. }
  15216. }
  15217. if (fullDetails) {
  15218. }
  15219. return ret;
  15220. };
  15221. Object.defineProperty(Camera.prototype, "globalPosition", {
  15222. get: function () {
  15223. return this._globalPosition;
  15224. },
  15225. enumerable: true,
  15226. configurable: true
  15227. });
  15228. Camera.prototype.getActiveMeshes = function () {
  15229. return this._activeMeshes;
  15230. };
  15231. Camera.prototype.isActiveMesh = function (mesh) {
  15232. return (this._activeMeshes.indexOf(mesh) !== -1);
  15233. };
  15234. //Cache
  15235. Camera.prototype._initCache = function () {
  15236. _super.prototype._initCache.call(this);
  15237. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15238. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15239. this._cache.mode = undefined;
  15240. this._cache.minZ = undefined;
  15241. this._cache.maxZ = undefined;
  15242. this._cache.fov = undefined;
  15243. this._cache.fovMode = undefined;
  15244. this._cache.aspectRatio = undefined;
  15245. this._cache.orthoLeft = undefined;
  15246. this._cache.orthoRight = undefined;
  15247. this._cache.orthoBottom = undefined;
  15248. this._cache.orthoTop = undefined;
  15249. this._cache.renderWidth = undefined;
  15250. this._cache.renderHeight = undefined;
  15251. };
  15252. Camera.prototype._updateCache = function (ignoreParentClass) {
  15253. if (!ignoreParentClass) {
  15254. _super.prototype._updateCache.call(this);
  15255. }
  15256. var engine = this.getEngine();
  15257. this._cache.position.copyFrom(this.position);
  15258. this._cache.upVector.copyFrom(this.upVector);
  15259. };
  15260. // Synchronized
  15261. Camera.prototype._isSynchronized = function () {
  15262. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15263. };
  15264. Camera.prototype._isSynchronizedViewMatrix = function () {
  15265. if (!_super.prototype._isSynchronized.call(this))
  15266. return false;
  15267. return this._cache.position.equals(this.position)
  15268. && this._cache.upVector.equals(this.upVector)
  15269. && this.isSynchronizedWithParent();
  15270. };
  15271. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15272. var check = this._cache.mode === this.mode
  15273. && this._cache.minZ === this.minZ
  15274. && this._cache.maxZ === this.maxZ;
  15275. if (!check) {
  15276. return false;
  15277. }
  15278. var engine = this.getEngine();
  15279. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15280. check = this._cache.fov === this.fov
  15281. && this._cache.fovMode === this.fovMode
  15282. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15283. }
  15284. else {
  15285. check = this._cache.orthoLeft === this.orthoLeft
  15286. && this._cache.orthoRight === this.orthoRight
  15287. && this._cache.orthoBottom === this.orthoBottom
  15288. && this._cache.orthoTop === this.orthoTop
  15289. && this._cache.renderWidth === engine.getRenderWidth()
  15290. && this._cache.renderHeight === engine.getRenderHeight();
  15291. }
  15292. return check;
  15293. };
  15294. // Controls
  15295. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15296. };
  15297. Camera.prototype.detachControl = function (element) {
  15298. };
  15299. Camera.prototype.update = function () {
  15300. this._checkInputs();
  15301. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15302. this._updateRigCameras();
  15303. }
  15304. };
  15305. Camera.prototype._checkInputs = function () {
  15306. this.onAfterCheckInputsObservable.notifyObservers(this);
  15307. };
  15308. Object.defineProperty(Camera.prototype, "rigCameras", {
  15309. get: function () {
  15310. return this._rigCameras;
  15311. },
  15312. enumerable: true,
  15313. configurable: true
  15314. });
  15315. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15316. get: function () {
  15317. return this._rigPostProcess;
  15318. },
  15319. enumerable: true,
  15320. configurable: true
  15321. });
  15322. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15323. // invalidate framebuffer
  15324. if (this._postProcesses.length > 0) {
  15325. this._postProcesses[0].markTextureDirty();
  15326. }
  15327. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15328. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15329. var cam = this._rigCameras[i];
  15330. var rigPostProcess = cam._rigPostProcess;
  15331. // for VR rig, there does not have to be a post process
  15332. if (rigPostProcess) {
  15333. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15334. if (isPass) {
  15335. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15336. cam.isIntermediate = this._postProcesses.length === 0;
  15337. }
  15338. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15339. rigPostProcess.markTextureDirty();
  15340. }
  15341. else {
  15342. cam._postProcesses = this._postProcesses.slice(0);
  15343. }
  15344. }
  15345. };
  15346. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15347. if (insertAt === void 0) { insertAt = null; }
  15348. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15349. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15350. return 0;
  15351. }
  15352. if (insertAt == null || insertAt < 0) {
  15353. this._postProcesses.push(postProcess);
  15354. }
  15355. else {
  15356. this._postProcesses.splice(insertAt, 0, postProcess);
  15357. }
  15358. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15359. return this._postProcesses.indexOf(postProcess);
  15360. };
  15361. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15362. if (atIndices === void 0) { atIndices = null; }
  15363. var result = [];
  15364. var i;
  15365. var index;
  15366. if (!atIndices) {
  15367. var idx = this._postProcesses.indexOf(postProcess);
  15368. if (idx !== -1) {
  15369. this._postProcesses.splice(idx, 1);
  15370. }
  15371. }
  15372. else {
  15373. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15374. // iterate descending, so can just splice as we go
  15375. for (i = atIndices.length - 1; i >= 0; i--) {
  15376. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15377. result.push(i);
  15378. continue;
  15379. }
  15380. index = atIndices[i];
  15381. this._postProcesses.splice(index, 1);
  15382. }
  15383. }
  15384. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15385. return result;
  15386. };
  15387. Camera.prototype.getWorldMatrix = function () {
  15388. if (!this._worldMatrix) {
  15389. this._worldMatrix = BABYLON.Matrix.Identity();
  15390. }
  15391. var viewMatrix = this.getViewMatrix();
  15392. viewMatrix.invertToRef(this._worldMatrix);
  15393. return this._worldMatrix;
  15394. };
  15395. Camera.prototype._getViewMatrix = function () {
  15396. return BABYLON.Matrix.Identity();
  15397. };
  15398. Camera.prototype.getViewMatrix = function (force) {
  15399. if (!force && this._isSynchronizedViewMatrix()) {
  15400. return this._computedViewMatrix;
  15401. }
  15402. this.updateCache();
  15403. this._computedViewMatrix = this._getViewMatrix();
  15404. this._currentRenderId = this.getScene().getRenderId();
  15405. this._refreshFrustumPlanes = true;
  15406. if (!this.parent || !this.parent.getWorldMatrix) {
  15407. this._globalPosition.copyFrom(this.position);
  15408. }
  15409. else {
  15410. if (!this._worldMatrix) {
  15411. this._worldMatrix = BABYLON.Matrix.Identity();
  15412. }
  15413. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15414. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15415. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15416. this._computedViewMatrix.invert();
  15417. this._markSyncedWithParent();
  15418. }
  15419. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15420. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15421. }
  15422. this.onViewMatrixChangedObservable.notifyObservers(this);
  15423. return this._computedViewMatrix;
  15424. };
  15425. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15426. this._doNotComputeProjectionMatrix = true;
  15427. if (projection !== undefined) {
  15428. this._projectionMatrix = projection;
  15429. }
  15430. };
  15431. ;
  15432. Camera.prototype.unfreezeProjectionMatrix = function () {
  15433. this._doNotComputeProjectionMatrix = false;
  15434. };
  15435. ;
  15436. Camera.prototype.getProjectionMatrix = function (force) {
  15437. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15438. return this._projectionMatrix;
  15439. }
  15440. // Cache
  15441. this._cache.mode = this.mode;
  15442. this._cache.minZ = this.minZ;
  15443. this._cache.maxZ = this.maxZ;
  15444. // Matrix
  15445. this._refreshFrustumPlanes = true;
  15446. var engine = this.getEngine();
  15447. var scene = this.getScene();
  15448. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15449. this._cache.fov = this.fov;
  15450. this._cache.fovMode = this.fovMode;
  15451. this._cache.aspectRatio = engine.getAspectRatio(this);
  15452. if (this.minZ <= 0) {
  15453. this.minZ = 0.1;
  15454. }
  15455. if (scene.useRightHandedSystem) {
  15456. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15457. }
  15458. else {
  15459. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15460. }
  15461. }
  15462. else {
  15463. var halfWidth = engine.getRenderWidth() / 2.0;
  15464. var halfHeight = engine.getRenderHeight() / 2.0;
  15465. if (scene.useRightHandedSystem) {
  15466. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15467. }
  15468. else {
  15469. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15470. }
  15471. this._cache.orthoLeft = this.orthoLeft;
  15472. this._cache.orthoRight = this.orthoRight;
  15473. this._cache.orthoBottom = this.orthoBottom;
  15474. this._cache.orthoTop = this.orthoTop;
  15475. this._cache.renderWidth = engine.getRenderWidth();
  15476. this._cache.renderHeight = engine.getRenderHeight();
  15477. }
  15478. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15479. return this._projectionMatrix;
  15480. };
  15481. Camera.prototype.getTranformationMatrix = function () {
  15482. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15483. return this._transformMatrix;
  15484. };
  15485. Camera.prototype.updateFrustumPlanes = function () {
  15486. if (!this._refreshFrustumPlanes) {
  15487. return;
  15488. }
  15489. this.getTranformationMatrix();
  15490. if (!this._frustumPlanes) {
  15491. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15492. }
  15493. else {
  15494. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15495. }
  15496. this._refreshFrustumPlanes = false;
  15497. };
  15498. Camera.prototype.isInFrustum = function (target) {
  15499. this.updateFrustumPlanes();
  15500. return target.isInFrustum(this._frustumPlanes);
  15501. };
  15502. Camera.prototype.isCompletelyInFrustum = function (target) {
  15503. this.updateFrustumPlanes();
  15504. return target.isCompletelyInFrustum(this._frustumPlanes);
  15505. };
  15506. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15507. if (length === void 0) { length = 100; }
  15508. if (!transform) {
  15509. transform = this.getWorldMatrix();
  15510. }
  15511. if (!origin) {
  15512. origin = this.position;
  15513. }
  15514. var forward = new BABYLON.Vector3(0, 0, 1);
  15515. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15516. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15517. return new BABYLON.Ray(origin, direction, length);
  15518. };
  15519. Camera.prototype.dispose = function () {
  15520. // Observables
  15521. this.onViewMatrixChangedObservable.clear();
  15522. this.onProjectionMatrixChangedObservable.clear();
  15523. this.onAfterCheckInputsObservable.clear();
  15524. this.onRestoreStateObservable.clear();
  15525. // Inputs
  15526. if (this.inputs) {
  15527. this.inputs.clear();
  15528. }
  15529. // Animations
  15530. this.getScene().stopAnimation(this);
  15531. // Remove from scene
  15532. this.getScene().removeCamera(this);
  15533. while (this._rigCameras.length > 0) {
  15534. this._rigCameras.pop().dispose();
  15535. }
  15536. // Postprocesses
  15537. if (this._rigPostProcess) {
  15538. this._rigPostProcess.dispose(this);
  15539. this._rigPostProcess = null;
  15540. this._postProcesses = [];
  15541. }
  15542. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15543. this._rigPostProcess = null;
  15544. this._postProcesses = [];
  15545. }
  15546. else {
  15547. var i = this._postProcesses.length;
  15548. while (--i >= 0) {
  15549. this._postProcesses[i].dispose(this);
  15550. }
  15551. }
  15552. // Render targets
  15553. var i = this.customRenderTargets.length;
  15554. while (--i >= 0) {
  15555. this.customRenderTargets[i].dispose();
  15556. }
  15557. this.customRenderTargets = [];
  15558. // Active Meshes
  15559. this._activeMeshes.dispose();
  15560. _super.prototype.dispose.call(this);
  15561. };
  15562. Object.defineProperty(Camera.prototype, "leftCamera", {
  15563. // ---- Camera rigs section ----
  15564. get: function () {
  15565. if (this._rigCameras.length < 1) {
  15566. return undefined;
  15567. }
  15568. return this._rigCameras[0];
  15569. },
  15570. enumerable: true,
  15571. configurable: true
  15572. });
  15573. Object.defineProperty(Camera.prototype, "rightCamera", {
  15574. get: function () {
  15575. if (this._rigCameras.length < 2) {
  15576. return undefined;
  15577. }
  15578. return this._rigCameras[1];
  15579. },
  15580. enumerable: true,
  15581. configurable: true
  15582. });
  15583. Camera.prototype.getLeftTarget = function () {
  15584. if (this._rigCameras.length < 1) {
  15585. return undefined;
  15586. }
  15587. return this._rigCameras[0].getTarget();
  15588. };
  15589. Camera.prototype.getRightTarget = function () {
  15590. if (this._rigCameras.length < 2) {
  15591. return undefined;
  15592. }
  15593. return this._rigCameras[1].getTarget();
  15594. };
  15595. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15596. if (this.cameraRigMode === mode) {
  15597. return;
  15598. }
  15599. while (this._rigCameras.length > 0) {
  15600. this._rigCameras.pop().dispose();
  15601. }
  15602. this.cameraRigMode = mode;
  15603. this._cameraRigParams = {};
  15604. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15605. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15606. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15607. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15608. // create the rig cameras, unless none
  15609. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15610. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15611. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15612. }
  15613. switch (this.cameraRigMode) {
  15614. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15615. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15616. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15617. break;
  15618. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15619. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15620. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15621. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15622. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15623. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15624. break;
  15625. case Camera.RIG_MODE_VR:
  15626. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15627. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15628. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15629. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15630. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15631. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15632. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15633. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15634. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15635. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15636. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15637. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15638. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15639. if (metrics.compensateDistortion) {
  15640. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15641. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15642. }
  15643. break;
  15644. case Camera.RIG_MODE_WEBVR:
  15645. if (rigParams.vrDisplay) {
  15646. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15647. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15648. //Left eye
  15649. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15650. this._rigCameras[0].setCameraRigParameter("left", true);
  15651. //leaving this for future reference
  15652. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15653. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15654. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15655. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15656. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15657. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15658. this._rigCameras[0].parent = this;
  15659. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15660. //Right eye
  15661. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15662. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15663. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15664. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15665. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15666. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15667. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15668. this._rigCameras[1].parent = this;
  15669. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15670. if (Camera.UseAlternateWebVRRendering) {
  15671. this._rigCameras[1]._skipRendering = true;
  15672. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  15673. }
  15674. }
  15675. break;
  15676. }
  15677. this._cascadePostProcessesToRigCams();
  15678. this.update();
  15679. };
  15680. Camera.prototype._getVRProjectionMatrix = function () {
  15681. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15682. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15683. return this._projectionMatrix;
  15684. };
  15685. Camera.prototype._updateCameraRotationMatrix = function () {
  15686. //Here for WebVR
  15687. };
  15688. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15689. //Here for WebVR
  15690. };
  15691. /**
  15692. * This function MUST be overwritten by the different WebVR cameras available.
  15693. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15694. */
  15695. Camera.prototype._getWebVRProjectionMatrix = function () {
  15696. return BABYLON.Matrix.Identity();
  15697. };
  15698. /**
  15699. * This function MUST be overwritten by the different WebVR cameras available.
  15700. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15701. */
  15702. Camera.prototype._getWebVRViewMatrix = function () {
  15703. return BABYLON.Matrix.Identity();
  15704. };
  15705. Camera.prototype.setCameraRigParameter = function (name, value) {
  15706. if (!this._cameraRigParams) {
  15707. this._cameraRigParams = {};
  15708. }
  15709. this._cameraRigParams[name] = value;
  15710. //provisionnally:
  15711. if (name === "interaxialDistance") {
  15712. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15713. }
  15714. };
  15715. /**
  15716. * needs to be overridden by children so sub has required properties to be copied
  15717. */
  15718. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15719. return null;
  15720. };
  15721. /**
  15722. * May need to be overridden by children
  15723. */
  15724. Camera.prototype._updateRigCameras = function () {
  15725. for (var i = 0; i < this._rigCameras.length; i++) {
  15726. this._rigCameras[i].minZ = this.minZ;
  15727. this._rigCameras[i].maxZ = this.maxZ;
  15728. this._rigCameras[i].fov = this.fov;
  15729. }
  15730. // only update viewport when ANAGLYPH
  15731. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15732. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15733. }
  15734. };
  15735. Camera.prototype._setupInputs = function () {
  15736. };
  15737. Camera.prototype.serialize = function () {
  15738. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15739. // Type
  15740. serializationObject.type = this.getClassName();
  15741. // Parent
  15742. if (this.parent) {
  15743. serializationObject.parentId = this.parent.id;
  15744. }
  15745. if (this.inputs) {
  15746. this.inputs.serialize(serializationObject);
  15747. }
  15748. // Animations
  15749. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15750. serializationObject.ranges = this.serializeAnimationRanges();
  15751. return serializationObject;
  15752. };
  15753. Camera.prototype.clone = function (name) {
  15754. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15755. };
  15756. Camera.prototype.getDirection = function (localAxis) {
  15757. var result = BABYLON.Vector3.Zero();
  15758. this.getDirectionToRef(localAxis, result);
  15759. return result;
  15760. };
  15761. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15762. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15763. };
  15764. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15765. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15766. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15767. switch (type) {
  15768. case "ArcRotateCamera":
  15769. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15770. case "DeviceOrientationCamera":
  15771. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15772. case "FollowCamera":
  15773. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15774. case "ArcFollowCamera":
  15775. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15776. case "GamepadCamera":
  15777. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15778. case "TouchCamera":
  15779. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15780. case "VirtualJoysticksCamera":
  15781. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15782. case "WebVRFreeCamera":
  15783. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15784. case "WebVRGamepadCamera":
  15785. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15786. case "VRDeviceOrientationFreeCamera":
  15787. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15788. case "VRDeviceOrientationGamepadCamera":
  15789. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15790. case "AnaglyphArcRotateCamera":
  15791. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15792. case "AnaglyphFreeCamera":
  15793. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15794. case "AnaglyphGamepadCamera":
  15795. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15796. case "AnaglyphUniversalCamera":
  15797. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15798. case "StereoscopicArcRotateCamera":
  15799. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15800. case "StereoscopicFreeCamera":
  15801. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15802. case "StereoscopicGamepadCamera":
  15803. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15804. case "StereoscopicUniversalCamera":
  15805. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15806. case "FreeCamera":
  15807. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15808. default:
  15809. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15810. }
  15811. };
  15812. Camera.Parse = function (parsedCamera, scene) {
  15813. var type = parsedCamera.type;
  15814. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15815. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15816. // Parent
  15817. if (parsedCamera.parentId) {
  15818. camera._waitingParentId = parsedCamera.parentId;
  15819. }
  15820. //If camera has an input manager, let it parse inputs settings
  15821. if (camera.inputs) {
  15822. camera.inputs.parse(parsedCamera);
  15823. camera._setupInputs();
  15824. }
  15825. if (camera.setPosition) {
  15826. camera.position.copyFromFloats(0, 0, 0);
  15827. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15828. }
  15829. // Target
  15830. if (parsedCamera.target) {
  15831. if (camera.setTarget) {
  15832. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15833. }
  15834. }
  15835. // Apply 3d rig, when found
  15836. if (parsedCamera.cameraRigMode) {
  15837. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15838. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15839. }
  15840. // Animations
  15841. if (parsedCamera.animations) {
  15842. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15843. var parsedAnimation = parsedCamera.animations[animationIndex];
  15844. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15845. }
  15846. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15847. }
  15848. if (parsedCamera.autoAnimate) {
  15849. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15850. }
  15851. return camera;
  15852. };
  15853. return Camera;
  15854. }(BABYLON.Node));
  15855. // Statics
  15856. Camera._PERSPECTIVE_CAMERA = 0;
  15857. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15858. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15859. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15860. Camera._RIG_MODE_NONE = 0;
  15861. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15862. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15863. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15864. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15865. Camera._RIG_MODE_VR = 20;
  15866. Camera._RIG_MODE_WEBVR = 21;
  15867. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15868. Camera.UseAlternateWebVRRendering = false;
  15869. __decorate([
  15870. BABYLON.serializeAsVector3()
  15871. ], Camera.prototype, "position", void 0);
  15872. __decorate([
  15873. BABYLON.serializeAsVector3()
  15874. ], Camera.prototype, "upVector", void 0);
  15875. __decorate([
  15876. BABYLON.serialize()
  15877. ], Camera.prototype, "orthoLeft", void 0);
  15878. __decorate([
  15879. BABYLON.serialize()
  15880. ], Camera.prototype, "orthoRight", void 0);
  15881. __decorate([
  15882. BABYLON.serialize()
  15883. ], Camera.prototype, "orthoBottom", void 0);
  15884. __decorate([
  15885. BABYLON.serialize()
  15886. ], Camera.prototype, "orthoTop", void 0);
  15887. __decorate([
  15888. BABYLON.serialize()
  15889. ], Camera.prototype, "fov", void 0);
  15890. __decorate([
  15891. BABYLON.serialize()
  15892. ], Camera.prototype, "minZ", void 0);
  15893. __decorate([
  15894. BABYLON.serialize()
  15895. ], Camera.prototype, "maxZ", void 0);
  15896. __decorate([
  15897. BABYLON.serialize()
  15898. ], Camera.prototype, "inertia", void 0);
  15899. __decorate([
  15900. BABYLON.serialize()
  15901. ], Camera.prototype, "mode", void 0);
  15902. __decorate([
  15903. BABYLON.serialize()
  15904. ], Camera.prototype, "layerMask", void 0);
  15905. __decorate([
  15906. BABYLON.serialize()
  15907. ], Camera.prototype, "fovMode", void 0);
  15908. __decorate([
  15909. BABYLON.serialize()
  15910. ], Camera.prototype, "cameraRigMode", void 0);
  15911. __decorate([
  15912. BABYLON.serialize()
  15913. ], Camera.prototype, "interaxialDistance", void 0);
  15914. __decorate([
  15915. BABYLON.serialize()
  15916. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15917. BABYLON.Camera = Camera;
  15918. })(BABYLON || (BABYLON = {}));
  15919. //# sourceMappingURL=babylon.camera.js.map
  15920. var BABYLON;
  15921. (function (BABYLON) {
  15922. var RenderingManager = (function () {
  15923. function RenderingManager(scene) {
  15924. this._renderingGroups = new Array();
  15925. this._autoClearDepthStencil = {};
  15926. this._customOpaqueSortCompareFn = {};
  15927. this._customAlphaTestSortCompareFn = {};
  15928. this._customTransparentSortCompareFn = {};
  15929. this._renderinGroupInfo = null;
  15930. this._scene = scene;
  15931. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15932. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15933. }
  15934. }
  15935. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15936. if (depth === void 0) { depth = true; }
  15937. if (stencil === void 0) { stencil = true; }
  15938. if (this._depthStencilBufferAlreadyCleaned) {
  15939. return;
  15940. }
  15941. this._scene.getEngine().clear(null, false, depth, stencil);
  15942. this._depthStencilBufferAlreadyCleaned = true;
  15943. };
  15944. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15945. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15946. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15947. var info = null;
  15948. if (observable) {
  15949. if (!this._renderinGroupInfo) {
  15950. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15951. }
  15952. info = this._renderinGroupInfo;
  15953. info.scene = this._scene;
  15954. info.camera = this._scene.activeCamera;
  15955. }
  15956. // Dispatch sprites
  15957. if (renderSprites) {
  15958. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15959. var manager = this._scene.spriteManagers[index];
  15960. this.dispatchSprites(manager);
  15961. }
  15962. }
  15963. // Render
  15964. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15965. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15966. var renderingGroup = this._renderingGroups[index];
  15967. if (!renderingGroup && !observable)
  15968. continue;
  15969. this._currentIndex = index;
  15970. var renderingGroupMask = 0;
  15971. // Fire PRECLEAR stage
  15972. if (observable) {
  15973. renderingGroupMask = Math.pow(2, index);
  15974. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15975. info.renderingGroupId = index;
  15976. observable.notifyObservers(info, renderingGroupMask);
  15977. }
  15978. // Clear depth/stencil if needed
  15979. if (RenderingManager.AUTOCLEAR) {
  15980. var autoClear = this._autoClearDepthStencil[index];
  15981. if (autoClear && autoClear.autoClear) {
  15982. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15983. }
  15984. }
  15985. if (observable) {
  15986. // Fire PREOPAQUE stage
  15987. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15988. observable.notifyObservers(info, renderingGroupMask);
  15989. // Fire PRETRANSPARENT stage
  15990. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15991. observable.notifyObservers(info, renderingGroupMask);
  15992. }
  15993. if (renderingGroup)
  15994. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15995. // Fire POSTTRANSPARENT stage
  15996. if (observable) {
  15997. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15998. observable.notifyObservers(info, renderingGroupMask);
  15999. }
  16000. }
  16001. };
  16002. RenderingManager.prototype.reset = function () {
  16003. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16004. var renderingGroup = this._renderingGroups[index];
  16005. if (renderingGroup) {
  16006. renderingGroup.prepare();
  16007. }
  16008. }
  16009. };
  16010. RenderingManager.prototype.dispose = function () {
  16011. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16012. var renderingGroup = this._renderingGroups[index];
  16013. if (renderingGroup) {
  16014. renderingGroup.dispose();
  16015. }
  16016. }
  16017. this._renderingGroups.length = 0;
  16018. };
  16019. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16020. if (!this._renderingGroups[renderingGroupId]) {
  16021. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16022. }
  16023. };
  16024. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16025. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16026. this._prepareRenderingGroup(renderingGroupId);
  16027. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16028. };
  16029. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16030. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16031. this._prepareRenderingGroup(renderingGroupId);
  16032. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16033. };
  16034. RenderingManager.prototype.dispatch = function (subMesh) {
  16035. var mesh = subMesh.getMesh();
  16036. var renderingGroupId = mesh.renderingGroupId || 0;
  16037. this._prepareRenderingGroup(renderingGroupId);
  16038. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16039. };
  16040. /**
  16041. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16042. * This allowed control for front to back rendering or reversly depending of the special needs.
  16043. *
  16044. * @param renderingGroupId The rendering group id corresponding to its index
  16045. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16046. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16047. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16048. */
  16049. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16050. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16051. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16052. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16053. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16054. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16055. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16056. if (this._renderingGroups[renderingGroupId]) {
  16057. var group = this._renderingGroups[renderingGroupId];
  16058. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16059. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16060. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16061. }
  16062. };
  16063. /**
  16064. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16065. *
  16066. * @param renderingGroupId The rendering group id corresponding to its index
  16067. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16068. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16069. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16070. */
  16071. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16072. if (depth === void 0) { depth = true; }
  16073. if (stencil === void 0) { stencil = true; }
  16074. this._autoClearDepthStencil[renderingGroupId] = {
  16075. autoClear: autoClearDepthStencil,
  16076. depth: depth,
  16077. stencil: stencil
  16078. };
  16079. };
  16080. return RenderingManager;
  16081. }());
  16082. /**
  16083. * The max id used for rendering groups (not included)
  16084. */
  16085. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16086. /**
  16087. * The min id used for rendering groups (included)
  16088. */
  16089. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16090. /**
  16091. * Used to globally prevent autoclearing scenes.
  16092. */
  16093. RenderingManager.AUTOCLEAR = true;
  16094. BABYLON.RenderingManager = RenderingManager;
  16095. })(BABYLON || (BABYLON = {}));
  16096. //# sourceMappingURL=babylon.renderingManager.js.map
  16097. var BABYLON;
  16098. (function (BABYLON) {
  16099. var RenderingGroup = (function () {
  16100. /**
  16101. * Creates a new rendering group.
  16102. * @param index The rendering group index
  16103. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16104. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16105. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16106. */
  16107. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16108. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16109. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16110. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16111. this.index = index;
  16112. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16113. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16114. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16115. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16116. this._particleSystems = new BABYLON.SmartArray(256);
  16117. this._spriteManagers = new BABYLON.SmartArray(256);
  16118. this._edgesRenderers = new BABYLON.SmartArray(16);
  16119. this._scene = scene;
  16120. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16121. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16122. this.transparentSortCompareFn = transparentSortCompareFn;
  16123. }
  16124. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16125. /**
  16126. * Set the opaque sort comparison function.
  16127. * If null the sub meshes will be render in the order they were created
  16128. */
  16129. set: function (value) {
  16130. this._opaqueSortCompareFn = value;
  16131. if (value) {
  16132. this._renderOpaque = this.renderOpaqueSorted;
  16133. }
  16134. else {
  16135. this._renderOpaque = RenderingGroup.renderUnsorted;
  16136. }
  16137. },
  16138. enumerable: true,
  16139. configurable: true
  16140. });
  16141. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16142. /**
  16143. * Set the alpha test sort comparison function.
  16144. * If null the sub meshes will be render in the order they were created
  16145. */
  16146. set: function (value) {
  16147. this._alphaTestSortCompareFn = value;
  16148. if (value) {
  16149. this._renderAlphaTest = this.renderAlphaTestSorted;
  16150. }
  16151. else {
  16152. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16153. }
  16154. },
  16155. enumerable: true,
  16156. configurable: true
  16157. });
  16158. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16159. /**
  16160. * Set the transparent sort comparison function.
  16161. * If null the sub meshes will be render in the order they were created
  16162. */
  16163. set: function (value) {
  16164. if (value) {
  16165. this._transparentSortCompareFn = value;
  16166. }
  16167. else {
  16168. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16169. }
  16170. this._renderTransparent = this.renderTransparentSorted;
  16171. },
  16172. enumerable: true,
  16173. configurable: true
  16174. });
  16175. /**
  16176. * Render all the sub meshes contained in the group.
  16177. * @param customRenderFunction Used to override the default render behaviour of the group.
  16178. * @returns true if rendered some submeshes.
  16179. */
  16180. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16181. if (customRenderFunction) {
  16182. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16183. return;
  16184. }
  16185. var engine = this._scene.getEngine();
  16186. // Depth only
  16187. if (this._depthOnlySubMeshes.length !== 0) {
  16188. engine.setAlphaTesting(true);
  16189. engine.setColorWrite(false);
  16190. this._renderAlphaTest(this._depthOnlySubMeshes);
  16191. engine.setAlphaTesting(false);
  16192. engine.setColorWrite(true);
  16193. }
  16194. // Opaque
  16195. if (this._opaqueSubMeshes.length !== 0) {
  16196. this._renderOpaque(this._opaqueSubMeshes);
  16197. }
  16198. // Alpha test
  16199. if (this._alphaTestSubMeshes.length !== 0) {
  16200. engine.setAlphaTesting(true);
  16201. this._renderAlphaTest(this._alphaTestSubMeshes);
  16202. engine.setAlphaTesting(false);
  16203. }
  16204. var stencilState = engine.getStencilBuffer();
  16205. engine.setStencilBuffer(false);
  16206. // Sprites
  16207. if (renderSprites) {
  16208. this._renderSprites();
  16209. }
  16210. // Particles
  16211. if (renderParticles) {
  16212. this._renderParticles(activeMeshes);
  16213. }
  16214. if (this.onBeforeTransparentRendering) {
  16215. this.onBeforeTransparentRendering();
  16216. }
  16217. // Transparent
  16218. if (this._transparentSubMeshes.length !== 0) {
  16219. this._renderTransparent(this._transparentSubMeshes);
  16220. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16221. }
  16222. // Set back stencil to false in case it changes before the edge renderer.
  16223. engine.setStencilBuffer(false);
  16224. // Edges
  16225. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16226. this._edgesRenderers.data[edgesRendererIndex].render();
  16227. }
  16228. // Restore Stencil state.
  16229. engine.setStencilBuffer(stencilState);
  16230. };
  16231. /**
  16232. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16233. * @param subMeshes The submeshes to render
  16234. */
  16235. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16236. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16237. };
  16238. /**
  16239. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16240. * @param subMeshes The submeshes to render
  16241. */
  16242. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16243. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16244. };
  16245. /**
  16246. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16247. * @param subMeshes The submeshes to render
  16248. */
  16249. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16250. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16251. };
  16252. /**
  16253. * Renders the submeshes in a specified order.
  16254. * @param subMeshes The submeshes to sort before render
  16255. * @param sortCompareFn The comparison function use to sort
  16256. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16257. * @param transparent Specifies to activate blending if true
  16258. */
  16259. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16260. var subIndex = 0;
  16261. var subMesh;
  16262. for (; subIndex < subMeshes.length; subIndex++) {
  16263. subMesh = subMeshes.data[subIndex];
  16264. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16265. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16266. }
  16267. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16268. sortedArray.sort(sortCompareFn);
  16269. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16270. subMesh = sortedArray[subIndex];
  16271. if (transparent) {
  16272. var material = subMesh.getMaterial();
  16273. if (material.needDepthPrePass) {
  16274. var engine = material.getScene().getEngine();
  16275. engine.setColorWrite(false);
  16276. engine.setAlphaTesting(true);
  16277. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16278. subMesh.render(false);
  16279. engine.setAlphaTesting(false);
  16280. engine.setColorWrite(true);
  16281. }
  16282. }
  16283. subMesh.render(transparent);
  16284. }
  16285. };
  16286. /**
  16287. * Renders the submeshes in the order they were dispatched (no sort applied).
  16288. * @param subMeshes The submeshes to render
  16289. */
  16290. RenderingGroup.renderUnsorted = function (subMeshes) {
  16291. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16292. var submesh = subMeshes.data[subIndex];
  16293. submesh.render(false);
  16294. }
  16295. };
  16296. /**
  16297. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16298. * are rendered back to front if in the same alpha index.
  16299. *
  16300. * @param a The first submesh
  16301. * @param b The second submesh
  16302. * @returns The result of the comparison
  16303. */
  16304. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16305. // Alpha index first
  16306. if (a._alphaIndex > b._alphaIndex) {
  16307. return 1;
  16308. }
  16309. if (a._alphaIndex < b._alphaIndex) {
  16310. return -1;
  16311. }
  16312. // Then distance to camera
  16313. return RenderingGroup.backToFrontSortCompare(a, b);
  16314. };
  16315. /**
  16316. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16317. * are rendered back to front.
  16318. *
  16319. * @param a The first submesh
  16320. * @param b The second submesh
  16321. * @returns The result of the comparison
  16322. */
  16323. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16324. // Then distance to camera
  16325. if (a._distanceToCamera < b._distanceToCamera) {
  16326. return 1;
  16327. }
  16328. if (a._distanceToCamera > b._distanceToCamera) {
  16329. return -1;
  16330. }
  16331. return 0;
  16332. };
  16333. /**
  16334. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16335. * are rendered front to back (prevent overdraw).
  16336. *
  16337. * @param a The first submesh
  16338. * @param b The second submesh
  16339. * @returns The result of the comparison
  16340. */
  16341. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16342. // Then distance to camera
  16343. if (a._distanceToCamera < b._distanceToCamera) {
  16344. return -1;
  16345. }
  16346. if (a._distanceToCamera > b._distanceToCamera) {
  16347. return 1;
  16348. }
  16349. return 0;
  16350. };
  16351. /**
  16352. * Resets the different lists of submeshes to prepare a new frame.
  16353. */
  16354. RenderingGroup.prototype.prepare = function () {
  16355. this._opaqueSubMeshes.reset();
  16356. this._transparentSubMeshes.reset();
  16357. this._alphaTestSubMeshes.reset();
  16358. this._depthOnlySubMeshes.reset();
  16359. this._particleSystems.reset();
  16360. this._spriteManagers.reset();
  16361. this._edgesRenderers.reset();
  16362. };
  16363. RenderingGroup.prototype.dispose = function () {
  16364. this._opaqueSubMeshes.dispose();
  16365. this._transparentSubMeshes.dispose();
  16366. this._alphaTestSubMeshes.dispose();
  16367. this._depthOnlySubMeshes.dispose();
  16368. this._particleSystems.dispose();
  16369. this._spriteManagers.dispose();
  16370. this._edgesRenderers.dispose();
  16371. };
  16372. /**
  16373. * Inserts the submesh in its correct queue depending on its material.
  16374. * @param subMesh The submesh to dispatch
  16375. */
  16376. RenderingGroup.prototype.dispatch = function (subMesh) {
  16377. var material = subMesh.getMaterial();
  16378. var mesh = subMesh.getMesh();
  16379. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16380. this._transparentSubMeshes.push(subMesh);
  16381. }
  16382. else if (material.needAlphaTesting()) {
  16383. if (material.needDepthPrePass) {
  16384. this._depthOnlySubMeshes.push(subMesh);
  16385. }
  16386. this._alphaTestSubMeshes.push(subMesh);
  16387. }
  16388. else {
  16389. if (material.needDepthPrePass) {
  16390. this._depthOnlySubMeshes.push(subMesh);
  16391. }
  16392. this._opaqueSubMeshes.push(subMesh); // Opaque
  16393. }
  16394. if (mesh._edgesRenderer) {
  16395. this._edgesRenderers.push(mesh._edgesRenderer);
  16396. }
  16397. };
  16398. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16399. this._spriteManagers.push(spriteManager);
  16400. };
  16401. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16402. this._particleSystems.push(particleSystem);
  16403. };
  16404. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16405. if (this._particleSystems.length === 0) {
  16406. return;
  16407. }
  16408. // Particles
  16409. var activeCamera = this._scene.activeCamera;
  16410. this._scene._particlesDuration.beginMonitoring();
  16411. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16412. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16413. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16414. continue;
  16415. }
  16416. var emitter = particleSystem.emitter;
  16417. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16418. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16419. }
  16420. }
  16421. this._scene._particlesDuration.endMonitoring(false);
  16422. };
  16423. RenderingGroup.prototype._renderSprites = function () {
  16424. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16425. return;
  16426. }
  16427. // Sprites
  16428. var activeCamera = this._scene.activeCamera;
  16429. this._scene._spritesDuration.beginMonitoring();
  16430. for (var id = 0; id < this._spriteManagers.length; id++) {
  16431. var spriteManager = this._spriteManagers.data[id];
  16432. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16433. spriteManager.render();
  16434. }
  16435. }
  16436. this._scene._spritesDuration.endMonitoring(false);
  16437. };
  16438. return RenderingGroup;
  16439. }());
  16440. BABYLON.RenderingGroup = RenderingGroup;
  16441. })(BABYLON || (BABYLON = {}));
  16442. //# sourceMappingURL=babylon.renderingGroup.js.map
  16443. var BABYLON;
  16444. (function (BABYLON) {
  16445. var ClickInfo = (function () {
  16446. function ClickInfo() {
  16447. this._singleClick = false;
  16448. this._doubleClick = false;
  16449. this._hasSwiped = false;
  16450. this._ignore = false;
  16451. }
  16452. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16453. get: function () {
  16454. return this._singleClick;
  16455. },
  16456. set: function (b) {
  16457. this._singleClick = b;
  16458. },
  16459. enumerable: true,
  16460. configurable: true
  16461. });
  16462. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16463. get: function () {
  16464. return this._doubleClick;
  16465. },
  16466. set: function (b) {
  16467. this._doubleClick = b;
  16468. },
  16469. enumerable: true,
  16470. configurable: true
  16471. });
  16472. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16473. get: function () {
  16474. return this._hasSwiped;
  16475. },
  16476. set: function (b) {
  16477. this._hasSwiped = b;
  16478. },
  16479. enumerable: true,
  16480. configurable: true
  16481. });
  16482. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16483. get: function () {
  16484. return this._ignore;
  16485. },
  16486. set: function (b) {
  16487. this._ignore = b;
  16488. },
  16489. enumerable: true,
  16490. configurable: true
  16491. });
  16492. return ClickInfo;
  16493. }());
  16494. /**
  16495. * This class is used by the onRenderingGroupObservable
  16496. */
  16497. var RenderingGroupInfo = (function () {
  16498. function RenderingGroupInfo() {
  16499. }
  16500. return RenderingGroupInfo;
  16501. }());
  16502. /**
  16503. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16504. * This stage will be fired no matter what
  16505. */
  16506. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16507. /**
  16508. * Called before opaque object are rendered.
  16509. * This stage will be fired only if there's 3D Opaque content to render
  16510. */
  16511. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16512. /**
  16513. * Called after the opaque objects are rendered and before the transparent ones
  16514. * This stage will be fired only if there's 3D transparent content to render
  16515. */
  16516. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16517. /**
  16518. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16519. * This stage will be fired no matter what
  16520. */
  16521. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16522. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16523. /**
  16524. * Represents a scene to be rendered by the engine.
  16525. * @see http://doc.babylonjs.com/page.php?p=21911
  16526. */
  16527. var Scene = (function () {
  16528. /**
  16529. * @constructor
  16530. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16531. */
  16532. function Scene(engine) {
  16533. // Members
  16534. this.autoClear = true;
  16535. this.autoClearDepthAndStencil = true;
  16536. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16537. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16538. this.forceWireframe = false;
  16539. this._forcePointsCloud = false;
  16540. this.forceShowBoundingBoxes = false;
  16541. this.animationsEnabled = true;
  16542. this.constantlyUpdateMeshUnderPointer = false;
  16543. this.hoverCursor = "pointer";
  16544. this.defaultCursor = "";
  16545. // Metadata
  16546. this.metadata = null;
  16547. /**
  16548. * An event triggered when the scene is disposed.
  16549. * @type {BABYLON.Observable}
  16550. */
  16551. this.onDisposeObservable = new BABYLON.Observable();
  16552. /**
  16553. * An event triggered before rendering the scene
  16554. * @type {BABYLON.Observable}
  16555. */
  16556. this.onBeforeRenderObservable = new BABYLON.Observable();
  16557. /**
  16558. * An event triggered after rendering the scene
  16559. * @type {BABYLON.Observable}
  16560. */
  16561. this.onAfterRenderObservable = new BABYLON.Observable();
  16562. /**
  16563. * An event triggered when the scene is ready
  16564. * @type {BABYLON.Observable}
  16565. */
  16566. this.onReadyObservable = new BABYLON.Observable();
  16567. /**
  16568. * An event triggered before rendering a camera
  16569. * @type {BABYLON.Observable}
  16570. */
  16571. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16572. /**
  16573. * An event triggered after rendering a camera
  16574. * @type {BABYLON.Observable}
  16575. */
  16576. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16577. /**
  16578. * An event triggered when a camera is created
  16579. * @type {BABYLON.Observable}
  16580. */
  16581. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16582. /**
  16583. * An event triggered when a camera is removed
  16584. * @type {BABYLON.Observable}
  16585. */
  16586. this.onCameraRemovedObservable = new BABYLON.Observable();
  16587. /**
  16588. * An event triggered when a light is created
  16589. * @type {BABYLON.Observable}
  16590. */
  16591. this.onNewLightAddedObservable = new BABYLON.Observable();
  16592. /**
  16593. * An event triggered when a light is removed
  16594. * @type {BABYLON.Observable}
  16595. */
  16596. this.onLightRemovedObservable = new BABYLON.Observable();
  16597. /**
  16598. * An event triggered when a geometry is created
  16599. * @type {BABYLON.Observable}
  16600. */
  16601. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16602. /**
  16603. * An event triggered when a geometry is removed
  16604. * @type {BABYLON.Observable}
  16605. */
  16606. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16607. /**
  16608. * An event triggered when a mesh is created
  16609. * @type {BABYLON.Observable}
  16610. */
  16611. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16612. /**
  16613. * An event triggered when a mesh is removed
  16614. * @type {BABYLON.Observable}
  16615. */
  16616. this.onMeshRemovedObservable = new BABYLON.Observable();
  16617. /**
  16618. * An event triggered before calculating deterministic simulation step
  16619. * @type {BABYLON.Observable}
  16620. */
  16621. this.onBeforeStepObservable = new BABYLON.Observable();
  16622. /**
  16623. * An event triggered after calculating deterministic simulation step
  16624. * @type {BABYLON.Observable}
  16625. */
  16626. this.onAfterStepObservable = new BABYLON.Observable();
  16627. /**
  16628. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16629. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16630. * 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)
  16631. */
  16632. this.onRenderingGroupObservable = new BABYLON.Observable();
  16633. // Animations
  16634. this.animations = [];
  16635. /**
  16636. * 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).
  16637. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  16638. */
  16639. this.onPrePointerObservable = new BABYLON.Observable();
  16640. /**
  16641. * Observable event triggered each time an input event is received from the rendering canvas
  16642. */
  16643. this.onPointerObservable = new BABYLON.Observable();
  16644. this._meshPickProceed = false;
  16645. this._previousHasSwiped = false;
  16646. this._currentPickResult = null;
  16647. this._previousPickResult = null;
  16648. this._isButtonPressed = false;
  16649. this._doubleClickOccured = false;
  16650. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16651. this.cameraToUseForPointers = null;
  16652. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16653. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16654. this._startingPointerTime = 0;
  16655. this._previousStartingPointerTime = 0;
  16656. // Deterministic lockstep
  16657. this._timeAccumulator = 0;
  16658. this._currentStepId = 0;
  16659. this._currentInternalStep = 0;
  16660. // Keyboard
  16661. /**
  16662. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  16663. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  16664. */
  16665. this.onPreKeyboardObservable = new BABYLON.Observable();
  16666. /**
  16667. * Observable event triggered each time an keyboard event is received from the hosting window
  16668. */
  16669. this.onKeyboardObservable = new BABYLON.Observable();
  16670. // Coordinate system
  16671. /**
  16672. * use right-handed coordinate system on this scene.
  16673. * @type {boolean}
  16674. */
  16675. this._useRightHandedSystem = false;
  16676. // Fog
  16677. this._fogEnabled = true;
  16678. this._fogMode = Scene.FOGMODE_NONE;
  16679. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16680. this.fogDensity = 0.1;
  16681. this.fogStart = 0;
  16682. this.fogEnd = 1000.0;
  16683. // Lights
  16684. /**
  16685. * is shadow enabled on this scene.
  16686. * @type {boolean}
  16687. */
  16688. this._shadowsEnabled = true;
  16689. /**
  16690. * is light enabled on this scene.
  16691. * @type {boolean}
  16692. */
  16693. this._lightsEnabled = true;
  16694. /**
  16695. * All of the lights added to this scene.
  16696. * @see BABYLON.Light
  16697. * @type {BABYLON.Light[]}
  16698. */
  16699. this.lights = new Array();
  16700. // Cameras
  16701. /** All of the cameras added to this scene. */
  16702. this.cameras = new Array();
  16703. /** All of the active cameras added to this scene. */
  16704. this.activeCameras = new Array();
  16705. // Meshes
  16706. /**
  16707. * All of the (abstract) meshes added to this scene.
  16708. * @see BABYLON.AbstractMesh
  16709. * @type {BABYLON.AbstractMesh[]}
  16710. */
  16711. this.meshes = new Array();
  16712. // Geometries
  16713. this._geometries = new Array();
  16714. this.materials = new Array();
  16715. this.multiMaterials = new Array();
  16716. // Textures
  16717. this._texturesEnabled = true;
  16718. this.textures = new Array();
  16719. // Particles
  16720. this.particlesEnabled = true;
  16721. this.particleSystems = new Array();
  16722. // Sprites
  16723. this.spritesEnabled = true;
  16724. this.spriteManagers = new Array();
  16725. // Layers
  16726. this.layers = new Array();
  16727. this.highlightLayers = new Array();
  16728. // Skeletons
  16729. this._skeletonsEnabled = true;
  16730. this.skeletons = new Array();
  16731. // Morph targets
  16732. this.morphTargetManagers = new Array();
  16733. // Lens flares
  16734. this.lensFlaresEnabled = true;
  16735. this.lensFlareSystems = new Array();
  16736. // Collisions
  16737. this.collisionsEnabled = true;
  16738. /** Defines the gravity applied to this scene */
  16739. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16740. // Postprocesses
  16741. this.postProcesses = new Array();
  16742. this.postProcessesEnabled = true;
  16743. // Customs render targets
  16744. this.renderTargetsEnabled = true;
  16745. this.dumpNextRenderTargets = false;
  16746. this.customRenderTargets = new Array();
  16747. // Imported meshes
  16748. this.importedMeshesFiles = new Array();
  16749. // Probes
  16750. this.probesEnabled = true;
  16751. this.reflectionProbes = new Array();
  16752. this._actionManagers = new Array();
  16753. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16754. // Procedural textures
  16755. this.proceduralTexturesEnabled = true;
  16756. this._proceduralTextures = new Array();
  16757. this.soundTracks = new Array();
  16758. this._audioEnabled = true;
  16759. this._headphone = false;
  16760. // Performance counters
  16761. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16762. this._totalLightsCounter = new BABYLON.PerfCounter();
  16763. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16764. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16765. this._totalVertices = new BABYLON.PerfCounter();
  16766. this._activeIndices = new BABYLON.PerfCounter();
  16767. this._activeParticles = new BABYLON.PerfCounter();
  16768. this._interFrameDuration = new BABYLON.PerfCounter();
  16769. this._lastFrameDuration = new BABYLON.PerfCounter();
  16770. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16771. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16772. this._particlesDuration = new BABYLON.PerfCounter();
  16773. this._renderDuration = new BABYLON.PerfCounter();
  16774. this._spritesDuration = new BABYLON.PerfCounter();
  16775. this._activeBones = new BABYLON.PerfCounter();
  16776. this._animationTime = 0;
  16777. this.animationTimeScale = 1;
  16778. this._renderId = 0;
  16779. this._executeWhenReadyTimeoutId = -1;
  16780. this._intermediateRendering = false;
  16781. this._viewUpdateFlag = -1;
  16782. this._projectionUpdateFlag = -1;
  16783. this._alternateViewUpdateFlag = -1;
  16784. this._alternateProjectionUpdateFlag = -1;
  16785. this._toBeDisposed = new BABYLON.SmartArray(256);
  16786. this._pendingData = []; //ANY
  16787. this._activeMeshes = new BABYLON.SmartArray(256);
  16788. this._processedMaterials = new BABYLON.SmartArray(256);
  16789. this._renderTargets = new BABYLON.SmartArray(256);
  16790. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16791. this._activeSkeletons = new BABYLON.SmartArray(32);
  16792. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16793. this._activeAnimatables = new Array();
  16794. this._transformMatrix = BABYLON.Matrix.Zero();
  16795. this._useAlternateCameraConfiguration = false;
  16796. this._alternateRendering = false;
  16797. this.requireLightSorting = false;
  16798. this._uniqueIdCounter = 0;
  16799. this._activeMeshesFrozen = false;
  16800. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16801. this._engine.scenes.push(this);
  16802. this._uid = null;
  16803. this._renderingManager = new BABYLON.RenderingManager(this);
  16804. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16805. if (BABYLON.OutlineRenderer) {
  16806. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16807. }
  16808. this.attachControl();
  16809. //simplification queue
  16810. if (BABYLON.SimplificationQueue) {
  16811. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16812. }
  16813. //collision coordinator initialization. For now legacy per default.
  16814. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16815. // Uniform Buffer
  16816. this._createUbo();
  16817. // Default Image processing definition.
  16818. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16819. }
  16820. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16821. /** The fog is deactivated */
  16822. get: function () {
  16823. return Scene._FOGMODE_NONE;
  16824. },
  16825. enumerable: true,
  16826. configurable: true
  16827. });
  16828. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16829. /** The fog density is following an exponential function */
  16830. get: function () {
  16831. return Scene._FOGMODE_EXP;
  16832. },
  16833. enumerable: true,
  16834. configurable: true
  16835. });
  16836. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16837. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16838. get: function () {
  16839. return Scene._FOGMODE_EXP2;
  16840. },
  16841. enumerable: true,
  16842. configurable: true
  16843. });
  16844. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16845. /** The fog density is following a linear function. */
  16846. get: function () {
  16847. return Scene._FOGMODE_LINEAR;
  16848. },
  16849. enumerable: true,
  16850. configurable: true
  16851. });
  16852. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16853. /**
  16854. * Texture used in all pbr material as the reflection texture.
  16855. * As in the majority of the scene they are the same (exception for multi room and so on),
  16856. * this is easier to reference from here than from all the materials.
  16857. */
  16858. get: function () {
  16859. return this._environmentTexture;
  16860. },
  16861. /**
  16862. * Texture used in all pbr material as the reflection texture.
  16863. * As in the majority of the scene they are the same (exception for multi room and so on),
  16864. * this is easier to set here than in all the materials.
  16865. */
  16866. set: function (value) {
  16867. this._environmentTexture = value;
  16868. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16869. },
  16870. enumerable: true,
  16871. configurable: true
  16872. });
  16873. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16874. /**
  16875. * Default image processing configuration used either in the rendering
  16876. * Forward main pass or through the imageProcessingPostProcess if present.
  16877. * As in the majority of the scene they are the same (exception for multi camera),
  16878. * this is easier to reference from here than from all the materials and post process.
  16879. *
  16880. * No setter as we it is a shared configuration, you can set the values instead.
  16881. */
  16882. get: function () {
  16883. return this._imageProcessingConfiguration;
  16884. },
  16885. enumerable: true,
  16886. configurable: true
  16887. });
  16888. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16889. get: function () {
  16890. return this._forcePointsCloud;
  16891. },
  16892. set: function (value) {
  16893. if (this._forcePointsCloud === value) {
  16894. return;
  16895. }
  16896. this._forcePointsCloud = value;
  16897. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16898. },
  16899. enumerable: true,
  16900. configurable: true
  16901. });
  16902. Object.defineProperty(Scene.prototype, "onDispose", {
  16903. /** A function to be executed when this scene is disposed. */
  16904. set: function (callback) {
  16905. if (this._onDisposeObserver) {
  16906. this.onDisposeObservable.remove(this._onDisposeObserver);
  16907. }
  16908. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16909. },
  16910. enumerable: true,
  16911. configurable: true
  16912. });
  16913. Object.defineProperty(Scene.prototype, "beforeRender", {
  16914. /** A function to be executed before rendering this scene */
  16915. set: function (callback) {
  16916. if (this._onBeforeRenderObserver) {
  16917. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16918. }
  16919. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16920. },
  16921. enumerable: true,
  16922. configurable: true
  16923. });
  16924. Object.defineProperty(Scene.prototype, "afterRender", {
  16925. /** A function to be executed after rendering this scene */
  16926. set: function (callback) {
  16927. if (this._onAfterRenderObserver) {
  16928. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16929. }
  16930. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16931. },
  16932. enumerable: true,
  16933. configurable: true
  16934. });
  16935. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16936. set: function (callback) {
  16937. if (this._onBeforeCameraRenderObserver) {
  16938. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16939. }
  16940. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16941. },
  16942. enumerable: true,
  16943. configurable: true
  16944. });
  16945. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16946. set: function (callback) {
  16947. if (this._onAfterCameraRenderObserver) {
  16948. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16949. }
  16950. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16951. },
  16952. enumerable: true,
  16953. configurable: true
  16954. });
  16955. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16956. get: function () {
  16957. if (!this._gamepadManager) {
  16958. this._gamepadManager = new BABYLON.GamepadManager();
  16959. }
  16960. return this._gamepadManager;
  16961. },
  16962. enumerable: true,
  16963. configurable: true
  16964. });
  16965. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16966. get: function () {
  16967. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16968. },
  16969. enumerable: true,
  16970. configurable: true
  16971. });
  16972. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16973. get: function () {
  16974. return this._useRightHandedSystem;
  16975. },
  16976. set: function (value) {
  16977. if (this._useRightHandedSystem === value) {
  16978. return;
  16979. }
  16980. this._useRightHandedSystem = value;
  16981. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. Scene.prototype.setStepId = function (newStepId) {
  16987. this._currentStepId = newStepId;
  16988. };
  16989. ;
  16990. Scene.prototype.getStepId = function () {
  16991. return this._currentStepId;
  16992. };
  16993. ;
  16994. Scene.prototype.getInternalStep = function () {
  16995. return this._currentInternalStep;
  16996. };
  16997. ;
  16998. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16999. get: function () {
  17000. return this._fogEnabled;
  17001. },
  17002. /**
  17003. * is fog enabled on this scene.
  17004. */
  17005. set: function (value) {
  17006. if (this._fogEnabled === value) {
  17007. return;
  17008. }
  17009. this._fogEnabled = value;
  17010. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17011. },
  17012. enumerable: true,
  17013. configurable: true
  17014. });
  17015. Object.defineProperty(Scene.prototype, "fogMode", {
  17016. get: function () {
  17017. return this._fogMode;
  17018. },
  17019. set: function (value) {
  17020. if (this._fogMode === value) {
  17021. return;
  17022. }
  17023. this._fogMode = value;
  17024. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17025. },
  17026. enumerable: true,
  17027. configurable: true
  17028. });
  17029. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17030. get: function () {
  17031. return this._shadowsEnabled;
  17032. },
  17033. set: function (value) {
  17034. if (this._shadowsEnabled === value) {
  17035. return;
  17036. }
  17037. this._shadowsEnabled = value;
  17038. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17039. },
  17040. enumerable: true,
  17041. configurable: true
  17042. });
  17043. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17044. get: function () {
  17045. return this._lightsEnabled;
  17046. },
  17047. set: function (value) {
  17048. if (this._lightsEnabled === value) {
  17049. return;
  17050. }
  17051. this._lightsEnabled = value;
  17052. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17053. },
  17054. enumerable: true,
  17055. configurable: true
  17056. });
  17057. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17058. /** The default material used on meshes when no material is affected */
  17059. get: function () {
  17060. if (!this._defaultMaterial) {
  17061. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17062. }
  17063. return this._defaultMaterial;
  17064. },
  17065. /** The default material used on meshes when no material is affected */
  17066. set: function (value) {
  17067. this._defaultMaterial = value;
  17068. },
  17069. enumerable: true,
  17070. configurable: true
  17071. });
  17072. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17073. get: function () {
  17074. return this._texturesEnabled;
  17075. },
  17076. set: function (value) {
  17077. if (this._texturesEnabled === value) {
  17078. return;
  17079. }
  17080. this._texturesEnabled = value;
  17081. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17082. },
  17083. enumerable: true,
  17084. configurable: true
  17085. });
  17086. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17087. get: function () {
  17088. return this._skeletonsEnabled;
  17089. },
  17090. set: function (value) {
  17091. if (this._skeletonsEnabled === value) {
  17092. return;
  17093. }
  17094. this._skeletonsEnabled = value;
  17095. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17096. },
  17097. enumerable: true,
  17098. configurable: true
  17099. });
  17100. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17101. get: function () {
  17102. if (!this._postProcessRenderPipelineManager) {
  17103. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17104. }
  17105. return this._postProcessRenderPipelineManager;
  17106. },
  17107. enumerable: true,
  17108. configurable: true
  17109. });
  17110. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17111. get: function () {
  17112. if (!this._mainSoundTrack) {
  17113. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17114. }
  17115. return this._mainSoundTrack;
  17116. },
  17117. enumerable: true,
  17118. configurable: true
  17119. });
  17120. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17121. get: function () {
  17122. return this._alternateRendering;
  17123. },
  17124. enumerable: true,
  17125. configurable: true
  17126. });
  17127. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17128. get: function () {
  17129. return this._frustumPlanes;
  17130. },
  17131. enumerable: true,
  17132. configurable: true
  17133. });
  17134. Object.defineProperty(Scene.prototype, "debugLayer", {
  17135. // Properties
  17136. get: function () {
  17137. if (!this._debugLayer) {
  17138. this._debugLayer = new BABYLON.DebugLayer(this);
  17139. }
  17140. return this._debugLayer;
  17141. },
  17142. enumerable: true,
  17143. configurable: true
  17144. });
  17145. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17146. get: function () {
  17147. return this._workerCollisions;
  17148. },
  17149. set: function (enabled) {
  17150. if (!BABYLON.CollisionCoordinatorLegacy) {
  17151. return;
  17152. }
  17153. enabled = (enabled && !!Worker);
  17154. this._workerCollisions = enabled;
  17155. if (this.collisionCoordinator) {
  17156. this.collisionCoordinator.destroy();
  17157. }
  17158. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17159. this.collisionCoordinator.init(this);
  17160. },
  17161. enumerable: true,
  17162. configurable: true
  17163. });
  17164. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17165. get: function () {
  17166. return this._selectionOctree;
  17167. },
  17168. enumerable: true,
  17169. configurable: true
  17170. });
  17171. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17172. /**
  17173. * The mesh that is currently under the pointer.
  17174. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17175. */
  17176. get: function () {
  17177. return this._pointerOverMesh;
  17178. },
  17179. enumerable: true,
  17180. configurable: true
  17181. });
  17182. Object.defineProperty(Scene.prototype, "pointerX", {
  17183. /**
  17184. * Current on-screen X position of the pointer
  17185. * @return {number} X position of the pointer
  17186. */
  17187. get: function () {
  17188. return this._pointerX;
  17189. },
  17190. enumerable: true,
  17191. configurable: true
  17192. });
  17193. Object.defineProperty(Scene.prototype, "pointerY", {
  17194. /**
  17195. * Current on-screen Y position of the pointer
  17196. * @return {number} Y position of the pointer
  17197. */
  17198. get: function () {
  17199. return this._pointerY;
  17200. },
  17201. enumerable: true,
  17202. configurable: true
  17203. });
  17204. Scene.prototype.getCachedMaterial = function () {
  17205. return this._cachedMaterial;
  17206. };
  17207. Scene.prototype.getCachedEffect = function () {
  17208. return this._cachedEffect;
  17209. };
  17210. Scene.prototype.getCachedVisibility = function () {
  17211. return this._cachedVisibility;
  17212. };
  17213. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17214. if (visibility === void 0) { visibility = 1; }
  17215. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17216. };
  17217. Scene.prototype.getBoundingBoxRenderer = function () {
  17218. if (!this._boundingBoxRenderer) {
  17219. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17220. }
  17221. return this._boundingBoxRenderer;
  17222. };
  17223. Scene.prototype.getOutlineRenderer = function () {
  17224. return this._outlineRenderer;
  17225. };
  17226. Scene.prototype.getEngine = function () {
  17227. return this._engine;
  17228. };
  17229. Scene.prototype.getTotalVertices = function () {
  17230. return this._totalVertices.current;
  17231. };
  17232. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17233. get: function () {
  17234. return this._totalVertices;
  17235. },
  17236. enumerable: true,
  17237. configurable: true
  17238. });
  17239. Scene.prototype.getActiveIndices = function () {
  17240. return this._activeIndices.current;
  17241. };
  17242. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17243. get: function () {
  17244. return this._activeIndices;
  17245. },
  17246. enumerable: true,
  17247. configurable: true
  17248. });
  17249. Scene.prototype.getActiveParticles = function () {
  17250. return this._activeParticles.current;
  17251. };
  17252. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17253. get: function () {
  17254. return this._activeParticles;
  17255. },
  17256. enumerable: true,
  17257. configurable: true
  17258. });
  17259. Scene.prototype.getActiveBones = function () {
  17260. return this._activeBones.current;
  17261. };
  17262. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17263. get: function () {
  17264. return this._activeBones;
  17265. },
  17266. enumerable: true,
  17267. configurable: true
  17268. });
  17269. // Stats
  17270. Scene.prototype.getInterFramePerfCounter = function () {
  17271. return this._interFrameDuration.current;
  17272. };
  17273. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  17274. get: function () {
  17275. return this._interFrameDuration;
  17276. },
  17277. enumerable: true,
  17278. configurable: true
  17279. });
  17280. Scene.prototype.getLastFrameDuration = function () {
  17281. return this._lastFrameDuration.current;
  17282. };
  17283. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17284. get: function () {
  17285. return this._lastFrameDuration;
  17286. },
  17287. enumerable: true,
  17288. configurable: true
  17289. });
  17290. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17291. return this._evaluateActiveMeshesDuration.current;
  17292. };
  17293. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17294. get: function () {
  17295. return this._evaluateActiveMeshesDuration;
  17296. },
  17297. enumerable: true,
  17298. configurable: true
  17299. });
  17300. Scene.prototype.getActiveMeshes = function () {
  17301. return this._activeMeshes;
  17302. };
  17303. Scene.prototype.getRenderTargetsDuration = function () {
  17304. return this._renderTargetsDuration.current;
  17305. };
  17306. Scene.prototype.getRenderDuration = function () {
  17307. return this._renderDuration.current;
  17308. };
  17309. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17310. get: function () {
  17311. return this._renderDuration;
  17312. },
  17313. enumerable: true,
  17314. configurable: true
  17315. });
  17316. Scene.prototype.getParticlesDuration = function () {
  17317. return this._particlesDuration.current;
  17318. };
  17319. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17320. get: function () {
  17321. return this._particlesDuration;
  17322. },
  17323. enumerable: true,
  17324. configurable: true
  17325. });
  17326. Scene.prototype.getSpritesDuration = function () {
  17327. return this._spritesDuration.current;
  17328. };
  17329. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17330. get: function () {
  17331. return this._spritesDuration;
  17332. },
  17333. enumerable: true,
  17334. configurable: true
  17335. });
  17336. Scene.prototype.getAnimationRatio = function () {
  17337. return this._animationRatio;
  17338. };
  17339. Scene.prototype.getRenderId = function () {
  17340. return this._renderId;
  17341. };
  17342. Scene.prototype.incrementRenderId = function () {
  17343. this._renderId++;
  17344. };
  17345. Scene.prototype._updatePointerPosition = function (evt) {
  17346. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17347. this._pointerX = evt.clientX - canvasRect.left;
  17348. this._pointerY = evt.clientY - canvasRect.top;
  17349. this._unTranslatedPointerX = this._pointerX;
  17350. this._unTranslatedPointerY = this._pointerY;
  17351. };
  17352. Scene.prototype._createUbo = function () {
  17353. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17354. this._sceneUbo.addUniform("viewProjection", 16);
  17355. this._sceneUbo.addUniform("view", 16);
  17356. };
  17357. Scene.prototype._createAlternateUbo = function () {
  17358. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17359. this._alternateSceneUbo.addUniform("viewProjection", 16);
  17360. this._alternateSceneUbo.addUniform("view", 16);
  17361. };
  17362. // Pointers handling
  17363. /**
  17364. * Use this method to simulate a pointer move on a mesh
  17365. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17366. */
  17367. Scene.prototype.simulatePointerMove = function (pickResult) {
  17368. var evt = new PointerEvent("pointermove");
  17369. return this._processPointerMove(pickResult, evt);
  17370. };
  17371. Scene.prototype._processPointerMove = function (pickResult, evt) {
  17372. var canvas = this._engine.getRenderingCanvas();
  17373. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17374. this.setPointerOverSprite(null);
  17375. this.setPointerOverMesh(pickResult.pickedMesh);
  17376. if (this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17377. if (this._pointerOverMesh.actionManager.hoverCursor) {
  17378. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  17379. }
  17380. else {
  17381. canvas.style.cursor = this.hoverCursor;
  17382. }
  17383. }
  17384. else {
  17385. canvas.style.cursor = this.defaultCursor;
  17386. }
  17387. }
  17388. else {
  17389. this.setPointerOverMesh(null);
  17390. // Sprites
  17391. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17392. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17393. this.setPointerOverSprite(pickResult.pickedSprite);
  17394. if (this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  17395. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  17396. }
  17397. else {
  17398. canvas.style.cursor = this.hoverCursor;
  17399. }
  17400. }
  17401. else {
  17402. this.setPointerOverSprite(null);
  17403. // Restore pointer
  17404. canvas.style.cursor = this.defaultCursor;
  17405. }
  17406. }
  17407. if (this.onPointerMove) {
  17408. this.onPointerMove(evt, pickResult);
  17409. }
  17410. if (this.onPointerObservable.hasObservers()) {
  17411. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17412. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17413. this.onPointerObservable.notifyObservers(pi, type);
  17414. }
  17415. return this;
  17416. };
  17417. /**
  17418. * Use this method to simulate a pointer down on a mesh
  17419. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17420. */
  17421. Scene.prototype.simulatePointerDown = function (pickResult) {
  17422. var evt = new PointerEvent("pointerdown");
  17423. return this._processPointerDown(pickResult, evt);
  17424. };
  17425. Scene.prototype._processPointerDown = function (pickResult, evt) {
  17426. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17427. this._pickedDownMesh = pickResult.pickedMesh;
  17428. var actionManager = pickResult.pickedMesh.actionManager;
  17429. if (actionManager) {
  17430. if (actionManager.hasPickTriggers) {
  17431. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17432. switch (evt.button) {
  17433. case 0:
  17434. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17435. break;
  17436. case 1:
  17437. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17438. break;
  17439. case 2:
  17440. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17441. break;
  17442. }
  17443. }
  17444. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17445. window.setTimeout((function () {
  17446. var _this = this;
  17447. 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);
  17448. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17449. if (this._isButtonPressed &&
  17450. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17451. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17452. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17453. this._startingPointerTime = 0;
  17454. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17455. }
  17456. }
  17457. }).bind(this), Scene.LongPressDelay);
  17458. }
  17459. }
  17460. }
  17461. if (this.onPointerDown) {
  17462. this.onPointerDown(evt, pickResult);
  17463. }
  17464. if (this.onPointerObservable.hasObservers()) {
  17465. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17466. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17467. this.onPointerObservable.notifyObservers(pi, type);
  17468. }
  17469. return this;
  17470. };
  17471. /**
  17472. * Use this method to simulate a pointer up on a mesh
  17473. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17474. */
  17475. Scene.prototype.simulatePointerUp = function (pickResult) {
  17476. var evt = new PointerEvent("pointerup");
  17477. var clickInfo = new ClickInfo();
  17478. clickInfo.singleClick = true;
  17479. return this._processPointerUp(pickResult, evt, clickInfo);
  17480. };
  17481. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  17482. if (pickResult && pickResult && pickResult.pickedMesh) {
  17483. this._pickedUpMesh = pickResult.pickedMesh;
  17484. if (this._pickedDownMesh === this._pickedUpMesh) {
  17485. if (this.onPointerPick) {
  17486. this.onPointerPick(evt, pickResult);
  17487. }
  17488. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17489. var type = BABYLON.PointerEventTypes.POINTERPICK;
  17490. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17491. this.onPointerObservable.notifyObservers(pi, type);
  17492. }
  17493. }
  17494. if (pickResult.pickedMesh.actionManager) {
  17495. if (clickInfo.ignore) {
  17496. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17497. }
  17498. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17499. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17500. }
  17501. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17502. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17503. }
  17504. }
  17505. }
  17506. if (this._pickedDownMesh &&
  17507. this._pickedDownMesh.actionManager &&
  17508. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17509. this._pickedDownMesh !== this._pickedUpMesh) {
  17510. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17511. }
  17512. if (this.onPointerUp) {
  17513. this.onPointerUp(evt, pickResult);
  17514. }
  17515. if (this.onPointerObservable.hasObservers()) {
  17516. if (!clickInfo.ignore) {
  17517. if (!clickInfo.hasSwiped) {
  17518. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17519. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17520. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17521. this.onPointerObservable.notifyObservers(pi, type);
  17522. }
  17523. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17524. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17525. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17526. this.onPointerObservable.notifyObservers(pi, type);
  17527. }
  17528. }
  17529. }
  17530. else {
  17531. var type = BABYLON.PointerEventTypes.POINTERUP;
  17532. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17533. this.onPointerObservable.notifyObservers(pi, type);
  17534. }
  17535. }
  17536. return this;
  17537. };
  17538. /**
  17539. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17540. * @param attachUp defines if you want to attach events to pointerup
  17541. * @param attachDown defines if you want to attach events to pointerdown
  17542. * @param attachMove defines if you want to attach events to pointermove
  17543. */
  17544. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17545. var _this = this;
  17546. if (attachUp === void 0) { attachUp = true; }
  17547. if (attachDown === void 0) { attachDown = true; }
  17548. if (attachMove === void 0) { attachMove = true; }
  17549. this._initActionManager = function (act, clickInfo) {
  17550. if (!_this._meshPickProceed) {
  17551. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17552. _this._currentPickResult = pickResult;
  17553. if (pickResult) {
  17554. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17555. }
  17556. _this._meshPickProceed = true;
  17557. }
  17558. return act;
  17559. };
  17560. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17561. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17562. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17563. btn !== _this._previousButtonPressed) {
  17564. _this._doubleClickOccured = false;
  17565. clickInfo.singleClick = true;
  17566. clickInfo.ignore = false;
  17567. cb(clickInfo, _this._currentPickResult);
  17568. }
  17569. };
  17570. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17571. var clickInfo = new ClickInfo();
  17572. _this._currentPickResult = null;
  17573. var act;
  17574. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  17575. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  17576. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17577. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17578. act = _this._initActionManager(act, clickInfo);
  17579. if (act)
  17580. checkPicking = act.hasPickTriggers;
  17581. }
  17582. if (checkPicking) {
  17583. var btn = evt.button;
  17584. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17585. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17586. if (!clickInfo.hasSwiped) {
  17587. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17588. if (!checkSingleClickImmediately) {
  17589. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  17590. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17591. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17592. act = _this._initActionManager(act, clickInfo);
  17593. if (act)
  17594. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17595. }
  17596. }
  17597. if (checkSingleClickImmediately) {
  17598. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17599. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17600. btn !== _this._previousButtonPressed) {
  17601. clickInfo.singleClick = true;
  17602. cb(clickInfo, _this._currentPickResult);
  17603. }
  17604. }
  17605. else {
  17606. // wait that no double click has been raised during the double click delay
  17607. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17608. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17609. }
  17610. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  17611. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17612. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17613. act = _this._initActionManager(act, clickInfo);
  17614. if (act)
  17615. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17616. }
  17617. if (checkDoubleClick) {
  17618. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17619. if (btn === _this._previousButtonPressed &&
  17620. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17621. !_this._doubleClickOccured) {
  17622. // pointer has not moved for 2 clicks, it's a double click
  17623. if (!clickInfo.hasSwiped &&
  17624. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17625. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17626. _this._previousStartingPointerTime = 0;
  17627. _this._doubleClickOccured = true;
  17628. clickInfo.doubleClick = true;
  17629. clickInfo.ignore = false;
  17630. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17631. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17632. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17633. cb(clickInfo, _this._currentPickResult);
  17634. }
  17635. else {
  17636. _this._doubleClickOccured = false;
  17637. _this._previousStartingPointerTime = _this._startingPointerTime;
  17638. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17639. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17640. _this._previousButtonPressed = btn;
  17641. _this._previousHasSwiped = clickInfo.hasSwiped;
  17642. if (Scene.ExclusiveDoubleClickMode) {
  17643. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17644. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17645. }
  17646. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17647. cb(clickInfo, _this._previousPickResult);
  17648. }
  17649. else {
  17650. cb(clickInfo, _this._currentPickResult);
  17651. }
  17652. }
  17653. }
  17654. else {
  17655. _this._doubleClickOccured = false;
  17656. _this._previousStartingPointerTime = _this._startingPointerTime;
  17657. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17658. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17659. _this._previousButtonPressed = btn;
  17660. _this._previousHasSwiped = clickInfo.hasSwiped;
  17661. }
  17662. }
  17663. }
  17664. }
  17665. clickInfo.ignore = true;
  17666. cb(clickInfo, _this._currentPickResult);
  17667. };
  17668. this._spritePredicate = function (sprite) {
  17669. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17670. };
  17671. this._onPointerMove = function (evt) {
  17672. _this._updatePointerPosition(evt);
  17673. // PreObservable support
  17674. if (_this.onPrePointerObservable.hasObservers()) {
  17675. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17676. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17677. _this.onPrePointerObservable.notifyObservers(pi, type);
  17678. if (pi.skipOnPointerObservable) {
  17679. return;
  17680. }
  17681. }
  17682. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17683. return;
  17684. }
  17685. if (!_this.pointerMovePredicate) {
  17686. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17687. }
  17688. // Meshes
  17689. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17690. _this._processPointerMove(pickResult, evt);
  17691. };
  17692. this._onPointerDown = function (evt) {
  17693. _this._isButtonPressed = true;
  17694. _this._pickedDownMesh = null;
  17695. _this._meshPickProceed = false;
  17696. _this._updatePointerPosition(evt);
  17697. // PreObservable support
  17698. if (_this.onPrePointerObservable.hasObservers()) {
  17699. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17700. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17701. _this.onPrePointerObservable.notifyObservers(pi, type);
  17702. if (pi.skipOnPointerObservable) {
  17703. return;
  17704. }
  17705. }
  17706. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17707. return;
  17708. }
  17709. _this._startingPointerPosition.x = _this._pointerX;
  17710. _this._startingPointerPosition.y = _this._pointerY;
  17711. _this._startingPointerTime = new Date().getTime();
  17712. if (!_this.pointerDownPredicate) {
  17713. _this.pointerDownPredicate = function (mesh) {
  17714. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17715. };
  17716. }
  17717. // Meshes
  17718. _this._pickedDownMesh = null;
  17719. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17720. _this._processPointerDown(pickResult, evt);
  17721. // Sprites
  17722. _this._pickedDownSprite = null;
  17723. if (_this.spriteManagers.length > 0) {
  17724. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers);
  17725. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17726. if (pickResult.pickedSprite.actionManager) {
  17727. _this._pickedDownSprite = pickResult.pickedSprite;
  17728. switch (evt.button) {
  17729. case 0:
  17730. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17731. break;
  17732. case 1:
  17733. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17734. break;
  17735. case 2:
  17736. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17737. break;
  17738. }
  17739. if (pickResult.pickedSprite.actionManager) {
  17740. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17741. }
  17742. }
  17743. }
  17744. }
  17745. };
  17746. this._onPointerUp = function (evt) {
  17747. if (!_this._isButtonPressed) {
  17748. return; // So we need to test it the pointer down was pressed before.
  17749. }
  17750. _this._isButtonPressed = false;
  17751. _this._pickedUpMesh = null;
  17752. _this._meshPickProceed = false;
  17753. _this._updatePointerPosition(evt);
  17754. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17755. // PreObservable support
  17756. if (this.onPrePointerObservable.hasObservers()) {
  17757. if (!clickInfo.ignore) {
  17758. if (!clickInfo.hasSwiped) {
  17759. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17760. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17761. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17762. this.onPrePointerObservable.notifyObservers(pi, type);
  17763. if (pi.skipOnPointerObservable) {
  17764. return;
  17765. }
  17766. }
  17767. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17768. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17769. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17770. this.onPrePointerObservable.notifyObservers(pi, type);
  17771. if (pi.skipOnPointerObservable) {
  17772. return;
  17773. }
  17774. }
  17775. }
  17776. }
  17777. else {
  17778. var type = BABYLON.PointerEventTypes.POINTERUP;
  17779. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17780. this.onPrePointerObservable.notifyObservers(pi, type);
  17781. if (pi.skipOnPointerObservable) {
  17782. return;
  17783. }
  17784. }
  17785. }
  17786. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17787. return;
  17788. }
  17789. if (!this.pointerUpPredicate) {
  17790. this.pointerUpPredicate = function (mesh) {
  17791. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17792. };
  17793. }
  17794. // Meshes
  17795. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17796. this._initActionManager(null, clickInfo);
  17797. }
  17798. if (!pickResult) {
  17799. pickResult = this._currentPickResult;
  17800. }
  17801. this._processPointerUp(pickResult, evt, clickInfo);
  17802. // Sprites
  17803. if (this.spriteManagers.length > 0) {
  17804. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17805. if (pickResult.hit && pickResult.pickedSprite) {
  17806. if (pickResult.pickedSprite.actionManager) {
  17807. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17808. if (pickResult.pickedSprite.actionManager) {
  17809. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17810. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17811. }
  17812. }
  17813. }
  17814. }
  17815. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17816. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17817. }
  17818. }
  17819. this._previousPickResult = this._currentPickResult;
  17820. }).bind(_this));
  17821. };
  17822. this._onKeyDown = function (evt) {
  17823. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  17824. if (_this.onPreKeyboardObservable.hasObservers()) {
  17825. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17826. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17827. if (pi.skipOnPointerObservable) {
  17828. return;
  17829. }
  17830. }
  17831. if (_this.onKeyboardObservable.hasObservers()) {
  17832. var pi = new BABYLON.KeyboardInfo(type, evt);
  17833. _this.onKeyboardObservable.notifyObservers(pi, type);
  17834. }
  17835. if (_this.actionManager) {
  17836. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17837. }
  17838. };
  17839. this._onKeyUp = function (evt) {
  17840. var type = BABYLON.KeyboardEventTypes.KEYUP;
  17841. if (_this.onPreKeyboardObservable.hasObservers()) {
  17842. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17843. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17844. if (pi.skipOnPointerObservable) {
  17845. return;
  17846. }
  17847. }
  17848. if (_this.onKeyboardObservable.hasObservers()) {
  17849. var pi = new BABYLON.KeyboardInfo(type, evt);
  17850. _this.onKeyboardObservable.notifyObservers(pi, type);
  17851. }
  17852. if (_this.actionManager) {
  17853. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17854. }
  17855. };
  17856. var engine = this.getEngine();
  17857. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  17858. canvas.addEventListener("keydown", _this._onKeyDown, false);
  17859. canvas.addEventListener("keyup", _this._onKeyUp, false);
  17860. });
  17861. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  17862. canvas.removeEventListener("keydown", _this._onKeyDown);
  17863. canvas.removeEventListener("keyup", _this._onKeyUp);
  17864. });
  17865. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17866. var canvas = this._engine.getRenderingCanvas();
  17867. if (attachMove) {
  17868. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17869. // Wheel
  17870. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17871. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17872. }
  17873. if (attachDown) {
  17874. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17875. }
  17876. if (attachUp) {
  17877. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17878. }
  17879. canvas.tabIndex = 1;
  17880. };
  17881. Scene.prototype.detachControl = function () {
  17882. var engine = this.getEngine();
  17883. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17884. var canvas = engine.getRenderingCanvas();
  17885. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17886. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17887. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17888. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  17889. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  17890. // Wheel
  17891. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17892. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17893. // Keyboard
  17894. canvas.removeEventListener("keydown", this._onKeyDown);
  17895. canvas.removeEventListener("keyup", this._onKeyUp);
  17896. // Observables
  17897. this.onKeyboardObservable.clear();
  17898. this.onPreKeyboardObservable.clear();
  17899. this.onPointerObservable.clear();
  17900. this.onPrePointerObservable.clear();
  17901. };
  17902. // Ready
  17903. Scene.prototype.isReady = function () {
  17904. if (this._pendingData.length > 0) {
  17905. return false;
  17906. }
  17907. var index;
  17908. // Geometries
  17909. for (index = 0; index < this._geometries.length; index++) {
  17910. var geometry = this._geometries[index];
  17911. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17912. return false;
  17913. }
  17914. }
  17915. // Meshes
  17916. for (index = 0; index < this.meshes.length; index++) {
  17917. var mesh = this.meshes[index];
  17918. if (!mesh.isEnabled()) {
  17919. continue;
  17920. }
  17921. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17922. continue;
  17923. }
  17924. if (!mesh.isReady()) {
  17925. return false;
  17926. }
  17927. var mat = mesh.material;
  17928. if (mat) {
  17929. if (!mat.isReady(mesh)) {
  17930. return false;
  17931. }
  17932. }
  17933. }
  17934. return true;
  17935. };
  17936. Scene.prototype.resetCachedMaterial = function () {
  17937. this._cachedMaterial = null;
  17938. this._cachedEffect = null;
  17939. this._cachedVisibility = null;
  17940. };
  17941. Scene.prototype.registerBeforeRender = function (func) {
  17942. this.onBeforeRenderObservable.add(func);
  17943. };
  17944. Scene.prototype.unregisterBeforeRender = function (func) {
  17945. this.onBeforeRenderObservable.removeCallback(func);
  17946. };
  17947. Scene.prototype.registerAfterRender = function (func) {
  17948. this.onAfterRenderObservable.add(func);
  17949. };
  17950. Scene.prototype.unregisterAfterRender = function (func) {
  17951. this.onAfterRenderObservable.removeCallback(func);
  17952. };
  17953. Scene.prototype._addPendingData = function (data) {
  17954. this._pendingData.push(data);
  17955. };
  17956. Scene.prototype._removePendingData = function (data) {
  17957. var index = this._pendingData.indexOf(data);
  17958. if (index !== -1) {
  17959. this._pendingData.splice(index, 1);
  17960. }
  17961. };
  17962. Scene.prototype.getWaitingItemsCount = function () {
  17963. return this._pendingData.length;
  17964. };
  17965. /**
  17966. * Registers a function to be executed when the scene is ready.
  17967. * @param {Function} func - the function to be executed.
  17968. */
  17969. Scene.prototype.executeWhenReady = function (func) {
  17970. var _this = this;
  17971. this.onReadyObservable.add(func);
  17972. if (this._executeWhenReadyTimeoutId !== -1) {
  17973. return;
  17974. }
  17975. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17976. _this._checkIsReady();
  17977. }, 150);
  17978. };
  17979. Scene.prototype._checkIsReady = function () {
  17980. var _this = this;
  17981. if (this.isReady()) {
  17982. this.onReadyObservable.notifyObservers(this);
  17983. this.onReadyObservable.clear();
  17984. this._executeWhenReadyTimeoutId = -1;
  17985. return;
  17986. }
  17987. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17988. _this._checkIsReady();
  17989. }, 150);
  17990. };
  17991. // Animations
  17992. /**
  17993. * Will start the animation sequence of a given target
  17994. * @param target - the target
  17995. * @param {number} from - from which frame should animation start
  17996. * @param {number} to - till which frame should animation run.
  17997. * @param {boolean} [loop] - should the animation loop
  17998. * @param {number} [speedRatio] - the speed in which to run the animation
  17999. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18000. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18001. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18002. * See BABYLON.Animatable
  18003. */
  18004. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18005. if (speedRatio === void 0) { speedRatio = 1.0; }
  18006. if (from > to && speedRatio > 0) {
  18007. speedRatio *= -1;
  18008. }
  18009. this.stopAnimation(target);
  18010. if (!animatable) {
  18011. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18012. }
  18013. // Local animations
  18014. if (target.animations) {
  18015. animatable.appendAnimations(target, target.animations);
  18016. }
  18017. // Children animations
  18018. if (target.getAnimatables) {
  18019. var animatables = target.getAnimatables();
  18020. for (var index = 0; index < animatables.length; index++) {
  18021. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18022. }
  18023. }
  18024. animatable.reset();
  18025. return animatable;
  18026. };
  18027. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18028. if (speedRatio === undefined) {
  18029. speedRatio = 1.0;
  18030. }
  18031. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18032. return animatable;
  18033. };
  18034. Scene.prototype.getAnimatableByTarget = function (target) {
  18035. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18036. if (this._activeAnimatables[index].target === target) {
  18037. return this._activeAnimatables[index];
  18038. }
  18039. }
  18040. return null;
  18041. };
  18042. Object.defineProperty(Scene.prototype, "Animatables", {
  18043. get: function () {
  18044. return this._activeAnimatables;
  18045. },
  18046. enumerable: true,
  18047. configurable: true
  18048. });
  18049. /**
  18050. * Will stop the animation of the given target
  18051. * @param target - the target
  18052. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18053. * @see beginAnimation
  18054. */
  18055. Scene.prototype.stopAnimation = function (target, animationName) {
  18056. var animatable = this.getAnimatableByTarget(target);
  18057. if (animatable) {
  18058. animatable.stop(animationName);
  18059. }
  18060. };
  18061. Scene.prototype._animate = function () {
  18062. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18063. return;
  18064. }
  18065. // Getting time
  18066. var now = BABYLON.Tools.Now;
  18067. if (!this._animationTimeLast) {
  18068. if (this._pendingData.length > 0) {
  18069. return;
  18070. }
  18071. this._animationTimeLast = now;
  18072. }
  18073. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18074. this._animationTime += deltaTime;
  18075. this._animationTimeLast = now;
  18076. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18077. this._activeAnimatables[index]._animate(this._animationTime);
  18078. }
  18079. };
  18080. // Matrix
  18081. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  18082. this._useAlternateCameraConfiguration = active;
  18083. };
  18084. Scene.prototype.getViewMatrix = function () {
  18085. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  18086. };
  18087. Scene.prototype.getProjectionMatrix = function () {
  18088. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  18089. };
  18090. Scene.prototype.getTransformMatrix = function () {
  18091. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  18092. };
  18093. Scene.prototype.setTransformMatrix = function (view, projection) {
  18094. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  18095. return;
  18096. }
  18097. this._viewUpdateFlag = view.updateFlag;
  18098. this._projectionUpdateFlag = projection.updateFlag;
  18099. this._viewMatrix = view;
  18100. this._projectionMatrix = projection;
  18101. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18102. // Update frustum
  18103. if (!this._frustumPlanes) {
  18104. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18105. }
  18106. else {
  18107. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18108. }
  18109. if (this._sceneUbo.useUbo) {
  18110. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  18111. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  18112. this._sceneUbo.update();
  18113. }
  18114. };
  18115. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  18116. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  18117. return;
  18118. }
  18119. this._alternateViewUpdateFlag = view.updateFlag;
  18120. this._alternateProjectionUpdateFlag = projection.updateFlag;
  18121. this._alternateViewMatrix = view;
  18122. this._alternateProjectionMatrix = projection;
  18123. if (!this._alternateTransformMatrix) {
  18124. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  18125. }
  18126. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  18127. if (!this._alternateSceneUbo) {
  18128. this._createAlternateUbo();
  18129. }
  18130. if (this._alternateSceneUbo.useUbo) {
  18131. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  18132. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  18133. this._alternateSceneUbo.update();
  18134. }
  18135. };
  18136. Scene.prototype.getSceneUniformBuffer = function () {
  18137. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  18138. };
  18139. // Methods
  18140. Scene.prototype.getUniqueId = function () {
  18141. var result = this._uniqueIdCounter;
  18142. this._uniqueIdCounter++;
  18143. return result;
  18144. };
  18145. Scene.prototype.addMesh = function (newMesh) {
  18146. newMesh.uniqueId = this.getUniqueId();
  18147. var position = this.meshes.push(newMesh);
  18148. //notify the collision coordinator
  18149. if (this.collisionCoordinator) {
  18150. this.collisionCoordinator.onMeshAdded(newMesh);
  18151. }
  18152. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18153. };
  18154. Scene.prototype.removeMesh = function (toRemove) {
  18155. var index = this.meshes.indexOf(toRemove);
  18156. if (index !== -1) {
  18157. // Remove from the scene if mesh found
  18158. this.meshes.splice(index, 1);
  18159. }
  18160. //notify the collision coordinator
  18161. if (this.collisionCoordinator) {
  18162. this.collisionCoordinator.onMeshRemoved(toRemove);
  18163. }
  18164. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18165. return index;
  18166. };
  18167. Scene.prototype.removeSkeleton = function (toRemove) {
  18168. var index = this.skeletons.indexOf(toRemove);
  18169. if (index !== -1) {
  18170. // Remove from the scene if found
  18171. this.skeletons.splice(index, 1);
  18172. }
  18173. return index;
  18174. };
  18175. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  18176. var index = this.morphTargetManagers.indexOf(toRemove);
  18177. if (index !== -1) {
  18178. // Remove from the scene if found
  18179. this.morphTargetManagers.splice(index, 1);
  18180. }
  18181. return index;
  18182. };
  18183. Scene.prototype.removeLight = function (toRemove) {
  18184. var index = this.lights.indexOf(toRemove);
  18185. if (index !== -1) {
  18186. // Remove from the scene if mesh found
  18187. this.lights.splice(index, 1);
  18188. this.sortLightsByPriority();
  18189. }
  18190. this.onLightRemovedObservable.notifyObservers(toRemove);
  18191. return index;
  18192. };
  18193. Scene.prototype.removeCamera = function (toRemove) {
  18194. var index = this.cameras.indexOf(toRemove);
  18195. if (index !== -1) {
  18196. // Remove from the scene if mesh found
  18197. this.cameras.splice(index, 1);
  18198. }
  18199. // Remove from activeCameras
  18200. var index2 = this.activeCameras.indexOf(toRemove);
  18201. if (index2 !== -1) {
  18202. // Remove from the scene if mesh found
  18203. this.activeCameras.splice(index2, 1);
  18204. }
  18205. // Reset the activeCamera
  18206. if (this.activeCamera === toRemove) {
  18207. if (this.cameras.length > 0) {
  18208. this.activeCamera = this.cameras[0];
  18209. }
  18210. else {
  18211. this.activeCamera = null;
  18212. }
  18213. }
  18214. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18215. return index;
  18216. };
  18217. Scene.prototype.addLight = function (newLight) {
  18218. newLight.uniqueId = this.getUniqueId();
  18219. this.lights.push(newLight);
  18220. this.sortLightsByPriority();
  18221. this.onNewLightAddedObservable.notifyObservers(newLight);
  18222. };
  18223. Scene.prototype.sortLightsByPriority = function () {
  18224. if (this.requireLightSorting) {
  18225. this.lights.sort(BABYLON.Light.compareLightsPriority);
  18226. }
  18227. };
  18228. Scene.prototype.addCamera = function (newCamera) {
  18229. newCamera.uniqueId = this.getUniqueId();
  18230. var position = this.cameras.push(newCamera);
  18231. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18232. };
  18233. /**
  18234. * Switch active camera
  18235. * @param {Camera} newCamera - new active camera
  18236. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18237. */
  18238. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18239. if (attachControl === void 0) { attachControl = true; }
  18240. var canvas = this._engine.getRenderingCanvas();
  18241. this.activeCamera.detachControl(canvas);
  18242. this.activeCamera = newCamera;
  18243. if (attachControl) {
  18244. newCamera.attachControl(canvas);
  18245. }
  18246. };
  18247. /**
  18248. * sets the active camera of the scene using its ID
  18249. * @param {string} id - the camera's ID
  18250. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18251. * @see activeCamera
  18252. */
  18253. Scene.prototype.setActiveCameraByID = function (id) {
  18254. var camera = this.getCameraByID(id);
  18255. if (camera) {
  18256. this.activeCamera = camera;
  18257. return camera;
  18258. }
  18259. return null;
  18260. };
  18261. /**
  18262. * sets the active camera of the scene using its name
  18263. * @param {string} name - the camera's name
  18264. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18265. * @see activeCamera
  18266. */
  18267. Scene.prototype.setActiveCameraByName = function (name) {
  18268. var camera = this.getCameraByName(name);
  18269. if (camera) {
  18270. this.activeCamera = camera;
  18271. return camera;
  18272. }
  18273. return null;
  18274. };
  18275. /**
  18276. * get a material using its id
  18277. * @param {string} the material's ID
  18278. * @return {BABYLON.Material|null} the material or null if none found.
  18279. */
  18280. Scene.prototype.getMaterialByID = function (id) {
  18281. for (var index = 0; index < this.materials.length; index++) {
  18282. if (this.materials[index].id === id) {
  18283. return this.materials[index];
  18284. }
  18285. }
  18286. return null;
  18287. };
  18288. /**
  18289. * get a material using its name
  18290. * @param {string} the material's name
  18291. * @return {BABYLON.Material|null} the material or null if none found.
  18292. */
  18293. Scene.prototype.getMaterialByName = function (name) {
  18294. for (var index = 0; index < this.materials.length; index++) {
  18295. if (this.materials[index].name === name) {
  18296. return this.materials[index];
  18297. }
  18298. }
  18299. return null;
  18300. };
  18301. Scene.prototype.getLensFlareSystemByName = function (name) {
  18302. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18303. if (this.lensFlareSystems[index].name === name) {
  18304. return this.lensFlareSystems[index];
  18305. }
  18306. }
  18307. return null;
  18308. };
  18309. Scene.prototype.getLensFlareSystemByID = function (id) {
  18310. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18311. if (this.lensFlareSystems[index].id === id) {
  18312. return this.lensFlareSystems[index];
  18313. }
  18314. }
  18315. return null;
  18316. };
  18317. Scene.prototype.getCameraByID = function (id) {
  18318. for (var index = 0; index < this.cameras.length; index++) {
  18319. if (this.cameras[index].id === id) {
  18320. return this.cameras[index];
  18321. }
  18322. }
  18323. return null;
  18324. };
  18325. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18326. for (var index = 0; index < this.cameras.length; index++) {
  18327. if (this.cameras[index].uniqueId === uniqueId) {
  18328. return this.cameras[index];
  18329. }
  18330. }
  18331. return null;
  18332. };
  18333. /**
  18334. * get a camera using its name
  18335. * @param {string} the camera's name
  18336. * @return {BABYLON.Camera|null} the camera or null if none found.
  18337. */
  18338. Scene.prototype.getCameraByName = function (name) {
  18339. for (var index = 0; index < this.cameras.length; index++) {
  18340. if (this.cameras[index].name === name) {
  18341. return this.cameras[index];
  18342. }
  18343. }
  18344. return null;
  18345. };
  18346. /**
  18347. * get a bone using its id
  18348. * @param {string} the bone's id
  18349. * @return {BABYLON.Bone|null} the bone or null if not found
  18350. */
  18351. Scene.prototype.getBoneByID = function (id) {
  18352. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18353. var skeleton = this.skeletons[skeletonIndex];
  18354. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18355. if (skeleton.bones[boneIndex].id === id) {
  18356. return skeleton.bones[boneIndex];
  18357. }
  18358. }
  18359. }
  18360. return null;
  18361. };
  18362. /**
  18363. * get a bone using its id
  18364. * @param {string} the bone's name
  18365. * @return {BABYLON.Bone|null} the bone or null if not found
  18366. */
  18367. Scene.prototype.getBoneByName = function (name) {
  18368. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18369. var skeleton = this.skeletons[skeletonIndex];
  18370. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18371. if (skeleton.bones[boneIndex].name === name) {
  18372. return skeleton.bones[boneIndex];
  18373. }
  18374. }
  18375. }
  18376. return null;
  18377. };
  18378. /**
  18379. * get a light node using its name
  18380. * @param {string} the light's name
  18381. * @return {BABYLON.Light|null} the light or null if none found.
  18382. */
  18383. Scene.prototype.getLightByName = function (name) {
  18384. for (var index = 0; index < this.lights.length; index++) {
  18385. if (this.lights[index].name === name) {
  18386. return this.lights[index];
  18387. }
  18388. }
  18389. return null;
  18390. };
  18391. /**
  18392. * get a light node using its ID
  18393. * @param {string} the light's id
  18394. * @return {BABYLON.Light|null} the light or null if none found.
  18395. */
  18396. Scene.prototype.getLightByID = function (id) {
  18397. for (var index = 0; index < this.lights.length; index++) {
  18398. if (this.lights[index].id === id) {
  18399. return this.lights[index];
  18400. }
  18401. }
  18402. return null;
  18403. };
  18404. /**
  18405. * get a light node using its scene-generated unique ID
  18406. * @param {number} the light's unique id
  18407. * @return {BABYLON.Light|null} the light or null if none found.
  18408. */
  18409. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18410. for (var index = 0; index < this.lights.length; index++) {
  18411. if (this.lights[index].uniqueId === uniqueId) {
  18412. return this.lights[index];
  18413. }
  18414. }
  18415. return null;
  18416. };
  18417. /**
  18418. * get a particle system by id
  18419. * @param id {number} the particle system id
  18420. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  18421. */
  18422. Scene.prototype.getParticleSystemByID = function (id) {
  18423. for (var index = 0; index < this.particleSystems.length; index++) {
  18424. if (this.particleSystems[index].id === id) {
  18425. return this.particleSystems[index];
  18426. }
  18427. }
  18428. return null;
  18429. };
  18430. /**
  18431. * get a geometry using its ID
  18432. * @param {string} the geometry's id
  18433. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18434. */
  18435. Scene.prototype.getGeometryByID = function (id) {
  18436. for (var index = 0; index < this._geometries.length; index++) {
  18437. if (this._geometries[index].id === id) {
  18438. return this._geometries[index];
  18439. }
  18440. }
  18441. return null;
  18442. };
  18443. /**
  18444. * add a new geometry to this scene.
  18445. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18446. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18447. * @return {boolean} was the geometry added or not
  18448. */
  18449. Scene.prototype.pushGeometry = function (geometry, force) {
  18450. if (!force && this.getGeometryByID(geometry.id)) {
  18451. return false;
  18452. }
  18453. this._geometries.push(geometry);
  18454. //notify the collision coordinator
  18455. if (this.collisionCoordinator) {
  18456. this.collisionCoordinator.onGeometryAdded(geometry);
  18457. }
  18458. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18459. return true;
  18460. };
  18461. /**
  18462. * Removes an existing geometry
  18463. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18464. * @return {boolean} was the geometry removed or not
  18465. */
  18466. Scene.prototype.removeGeometry = function (geometry) {
  18467. var index = this._geometries.indexOf(geometry);
  18468. if (index > -1) {
  18469. this._geometries.splice(index, 1);
  18470. //notify the collision coordinator
  18471. if (this.collisionCoordinator) {
  18472. this.collisionCoordinator.onGeometryDeleted(geometry);
  18473. }
  18474. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18475. return true;
  18476. }
  18477. return false;
  18478. };
  18479. Scene.prototype.getGeometries = function () {
  18480. return this._geometries;
  18481. };
  18482. /**
  18483. * Get the first added mesh found of a given ID
  18484. * @param {string} id - the id to search for
  18485. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18486. */
  18487. Scene.prototype.getMeshByID = function (id) {
  18488. for (var index = 0; index < this.meshes.length; index++) {
  18489. if (this.meshes[index].id === id) {
  18490. return this.meshes[index];
  18491. }
  18492. }
  18493. return null;
  18494. };
  18495. Scene.prototype.getMeshesByID = function (id) {
  18496. return this.meshes.filter(function (m) {
  18497. return m.id === id;
  18498. });
  18499. };
  18500. /**
  18501. * Get a mesh with its auto-generated unique id
  18502. * @param {number} uniqueId - the unique id to search for
  18503. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18504. */
  18505. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18506. for (var index = 0; index < this.meshes.length; index++) {
  18507. if (this.meshes[index].uniqueId === uniqueId) {
  18508. return this.meshes[index];
  18509. }
  18510. }
  18511. return null;
  18512. };
  18513. /**
  18514. * Get a the last added mesh found of a given ID
  18515. * @param {string} id - the id to search for
  18516. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18517. */
  18518. Scene.prototype.getLastMeshByID = function (id) {
  18519. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18520. if (this.meshes[index].id === id) {
  18521. return this.meshes[index];
  18522. }
  18523. }
  18524. return null;
  18525. };
  18526. /**
  18527. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18528. * @param {string} id - the id to search for
  18529. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18530. */
  18531. Scene.prototype.getLastEntryByID = function (id) {
  18532. var index;
  18533. for (index = this.meshes.length - 1; index >= 0; index--) {
  18534. if (this.meshes[index].id === id) {
  18535. return this.meshes[index];
  18536. }
  18537. }
  18538. for (index = this.cameras.length - 1; index >= 0; index--) {
  18539. if (this.cameras[index].id === id) {
  18540. return this.cameras[index];
  18541. }
  18542. }
  18543. for (index = this.lights.length - 1; index >= 0; index--) {
  18544. if (this.lights[index].id === id) {
  18545. return this.lights[index];
  18546. }
  18547. }
  18548. return null;
  18549. };
  18550. Scene.prototype.getNodeByID = function (id) {
  18551. var mesh = this.getMeshByID(id);
  18552. if (mesh) {
  18553. return mesh;
  18554. }
  18555. var light = this.getLightByID(id);
  18556. if (light) {
  18557. return light;
  18558. }
  18559. var camera = this.getCameraByID(id);
  18560. if (camera) {
  18561. return camera;
  18562. }
  18563. var bone = this.getBoneByID(id);
  18564. return bone;
  18565. };
  18566. Scene.prototype.getNodeByName = function (name) {
  18567. var mesh = this.getMeshByName(name);
  18568. if (mesh) {
  18569. return mesh;
  18570. }
  18571. var light = this.getLightByName(name);
  18572. if (light) {
  18573. return light;
  18574. }
  18575. var camera = this.getCameraByName(name);
  18576. if (camera) {
  18577. return camera;
  18578. }
  18579. var bone = this.getBoneByName(name);
  18580. return bone;
  18581. };
  18582. Scene.prototype.getMeshByName = function (name) {
  18583. for (var index = 0; index < this.meshes.length; index++) {
  18584. if (this.meshes[index].name === name) {
  18585. return this.meshes[index];
  18586. }
  18587. }
  18588. return null;
  18589. };
  18590. Scene.prototype.getSoundByName = function (name) {
  18591. var index;
  18592. if (BABYLON.AudioEngine) {
  18593. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18594. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18595. return this.mainSoundTrack.soundCollection[index];
  18596. }
  18597. }
  18598. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18599. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18600. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18601. return this.soundTracks[sdIndex].soundCollection[index];
  18602. }
  18603. }
  18604. }
  18605. }
  18606. return null;
  18607. };
  18608. Scene.prototype.getLastSkeletonByID = function (id) {
  18609. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18610. if (this.skeletons[index].id === id) {
  18611. return this.skeletons[index];
  18612. }
  18613. }
  18614. return null;
  18615. };
  18616. Scene.prototype.getSkeletonById = function (id) {
  18617. for (var index = 0; index < this.skeletons.length; index++) {
  18618. if (this.skeletons[index].id === id) {
  18619. return this.skeletons[index];
  18620. }
  18621. }
  18622. return null;
  18623. };
  18624. Scene.prototype.getSkeletonByName = function (name) {
  18625. for (var index = 0; index < this.skeletons.length; index++) {
  18626. if (this.skeletons[index].name === name) {
  18627. return this.skeletons[index];
  18628. }
  18629. }
  18630. return null;
  18631. };
  18632. Scene.prototype.getMorphTargetManagerById = function (id) {
  18633. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18634. if (this.morphTargetManagers[index].uniqueId === id) {
  18635. return this.morphTargetManagers[index];
  18636. }
  18637. }
  18638. return null;
  18639. };
  18640. Scene.prototype.isActiveMesh = function (mesh) {
  18641. return (this._activeMeshes.indexOf(mesh) !== -1);
  18642. };
  18643. /**
  18644. * Return a the first highlight layer of the scene with a given name.
  18645. * @param name The name of the highlight layer to look for.
  18646. * @return The highlight layer if found otherwise null.
  18647. */
  18648. Scene.prototype.getHighlightLayerByName = function (name) {
  18649. for (var index = 0; index < this.highlightLayers.length; index++) {
  18650. if (this.highlightLayers[index].name === name) {
  18651. return this.highlightLayers[index];
  18652. }
  18653. }
  18654. return null;
  18655. };
  18656. Object.defineProperty(Scene.prototype, "uid", {
  18657. /**
  18658. * Return a unique id as a string which can serve as an identifier for the scene
  18659. */
  18660. get: function () {
  18661. if (!this._uid) {
  18662. this._uid = BABYLON.Tools.RandomId();
  18663. }
  18664. return this._uid;
  18665. },
  18666. enumerable: true,
  18667. configurable: true
  18668. });
  18669. /**
  18670. * Add an externaly attached data from its key.
  18671. * This method call will fail and return false, if such key already exists.
  18672. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18673. * @param key the unique key that identifies the data
  18674. * @param data the data object to associate to the key for this Engine instance
  18675. * @return true if no such key were already present and the data was added successfully, false otherwise
  18676. */
  18677. Scene.prototype.addExternalData = function (key, data) {
  18678. if (!this._externalData) {
  18679. this._externalData = new BABYLON.StringDictionary();
  18680. }
  18681. return this._externalData.add(key, data);
  18682. };
  18683. /**
  18684. * Get an externaly attached data from its key
  18685. * @param key the unique key that identifies the data
  18686. * @return the associated data, if present (can be null), or undefined if not present
  18687. */
  18688. Scene.prototype.getExternalData = function (key) {
  18689. if (!this._externalData) {
  18690. return null;
  18691. }
  18692. return this._externalData.get(key);
  18693. };
  18694. /**
  18695. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18696. * @param key the unique key that identifies the data
  18697. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18698. * @return the associated data, can be null if the factory returned null.
  18699. */
  18700. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18701. if (!this._externalData) {
  18702. this._externalData = new BABYLON.StringDictionary();
  18703. }
  18704. return this._externalData.getOrAddWithFactory(key, factory);
  18705. };
  18706. /**
  18707. * Remove an externaly attached data from the Engine instance
  18708. * @param key the unique key that identifies the data
  18709. * @return true if the data was successfully removed, false if it doesn't exist
  18710. */
  18711. Scene.prototype.removeExternalData = function (key) {
  18712. return this._externalData.remove(key);
  18713. };
  18714. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18715. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18716. var material = subMesh.getMaterial();
  18717. if (mesh.showSubMeshesBoundingBox) {
  18718. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18719. }
  18720. if (material) {
  18721. // Render targets
  18722. if (material.getRenderTargetTextures) {
  18723. if (this._processedMaterials.indexOf(material) === -1) {
  18724. this._processedMaterials.push(material);
  18725. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18726. }
  18727. }
  18728. // Dispatch
  18729. this._activeIndices.addCount(subMesh.indexCount, false);
  18730. this._renderingManager.dispatch(subMesh);
  18731. }
  18732. }
  18733. };
  18734. Scene.prototype._isInIntermediateRendering = function () {
  18735. return this._intermediateRendering;
  18736. };
  18737. /**
  18738. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  18739. */
  18740. Scene.prototype.freezeActiveMeshes = function () {
  18741. this._evaluateActiveMeshes();
  18742. this._activeMeshesFrozen = true;
  18743. return this;
  18744. };
  18745. /**
  18746. * Use this function to restart evaluating active meshes on every frame
  18747. */
  18748. Scene.prototype.unfreezeActiveMeshes = function () {
  18749. this._activeMeshesFrozen = false;
  18750. return this;
  18751. };
  18752. Scene.prototype._evaluateActiveMeshes = function () {
  18753. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  18754. return;
  18755. }
  18756. this.activeCamera._activeMeshes.reset();
  18757. this._activeMeshes.reset();
  18758. this._renderingManager.reset();
  18759. this._processedMaterials.reset();
  18760. this._activeParticleSystems.reset();
  18761. this._activeSkeletons.reset();
  18762. this._softwareSkinnedMeshes.reset();
  18763. if (this._boundingBoxRenderer) {
  18764. this._boundingBoxRenderer.reset();
  18765. }
  18766. // Meshes
  18767. var meshes;
  18768. var len;
  18769. if (this._selectionOctree) {
  18770. var selection = this._selectionOctree.select(this._frustumPlanes);
  18771. meshes = selection.data;
  18772. len = selection.length;
  18773. }
  18774. else {
  18775. len = this.meshes.length;
  18776. meshes = this.meshes;
  18777. }
  18778. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18779. var mesh = meshes[meshIndex];
  18780. if (mesh.isBlocked) {
  18781. continue;
  18782. }
  18783. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18784. if (!mesh.isReady() || !mesh.isEnabled()) {
  18785. continue;
  18786. }
  18787. mesh.computeWorldMatrix();
  18788. // Intersections
  18789. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18790. this._meshesForIntersections.pushNoDuplicate(mesh);
  18791. }
  18792. // Switch to current LOD
  18793. var meshLOD = mesh.getLOD(this.activeCamera);
  18794. if (!meshLOD) {
  18795. continue;
  18796. }
  18797. mesh._preActivate();
  18798. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18799. this._activeMeshes.push(mesh);
  18800. this.activeCamera._activeMeshes.push(mesh);
  18801. mesh._activate(this._renderId);
  18802. if (meshLOD !== mesh) {
  18803. meshLOD._activate(this._renderId);
  18804. }
  18805. this._activeMesh(mesh, meshLOD);
  18806. }
  18807. }
  18808. // Particle systems
  18809. this._particlesDuration.beginMonitoring();
  18810. var beforeParticlesDate = BABYLON.Tools.Now;
  18811. if (this.particlesEnabled) {
  18812. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18813. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18814. var particleSystem = this.particleSystems[particleIndex];
  18815. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18816. continue;
  18817. }
  18818. var emitter = particleSystem.emitter;
  18819. if (!emitter.position || emitter.isEnabled()) {
  18820. this._activeParticleSystems.push(particleSystem);
  18821. particleSystem.animate();
  18822. this._renderingManager.dispatchParticles(particleSystem);
  18823. }
  18824. }
  18825. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18826. }
  18827. this._particlesDuration.endMonitoring(false);
  18828. };
  18829. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18830. if (mesh.skeleton && this.skeletonsEnabled) {
  18831. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18832. mesh.skeleton.prepare();
  18833. }
  18834. if (!mesh.computeBonesUsingShaders) {
  18835. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18836. }
  18837. }
  18838. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18839. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18840. }
  18841. if (mesh && mesh.subMeshes) {
  18842. // Submeshes Octrees
  18843. var len;
  18844. var subMeshes;
  18845. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18846. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18847. len = intersections.length;
  18848. subMeshes = intersections.data;
  18849. }
  18850. else {
  18851. subMeshes = mesh.subMeshes;
  18852. len = subMeshes.length;
  18853. }
  18854. for (var subIndex = 0; subIndex < len; subIndex++) {
  18855. var subMesh = subMeshes[subIndex];
  18856. this._evaluateSubMesh(subMesh, mesh);
  18857. }
  18858. }
  18859. };
  18860. Scene.prototype.updateTransformMatrix = function (force) {
  18861. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18862. };
  18863. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  18864. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  18865. };
  18866. Scene.prototype._renderForCamera = function (camera) {
  18867. if (camera && camera._skipRendering) {
  18868. return;
  18869. }
  18870. var engine = this._engine;
  18871. var startTime = BABYLON.Tools.Now;
  18872. this.activeCamera = camera;
  18873. if (!this.activeCamera)
  18874. throw new Error("Active camera not set");
  18875. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18876. // Viewport
  18877. engine.setViewport(this.activeCamera.viewport);
  18878. // Camera
  18879. this.resetCachedMaterial();
  18880. this._renderId++;
  18881. this.activeCamera.update();
  18882. this.updateTransformMatrix();
  18883. if (camera._alternateCamera) {
  18884. this.updateAlternateTransformMatrix(camera._alternateCamera);
  18885. this._alternateRendering = true;
  18886. }
  18887. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18888. // Meshes
  18889. this._evaluateActiveMeshesDuration.beginMonitoring();
  18890. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18891. this._evaluateActiveMeshes();
  18892. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18893. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18894. // Software skinning
  18895. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18896. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18897. mesh.applySkeleton(mesh.skeleton);
  18898. }
  18899. // Render targets
  18900. this._renderTargetsDuration.beginMonitoring();
  18901. var needsRestoreFrameBuffer = false;
  18902. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18903. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18904. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18905. }
  18906. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18907. this._intermediateRendering = true;
  18908. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18909. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18910. var renderTarget = this._renderTargets.data[renderIndex];
  18911. if (renderTarget._shouldRender()) {
  18912. this._renderId++;
  18913. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18914. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18915. }
  18916. }
  18917. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18918. this._intermediateRendering = false;
  18919. this._renderId++;
  18920. needsRestoreFrameBuffer = true; // Restore back buffer
  18921. }
  18922. // Render HighlightLayer Texture
  18923. var stencilState = this._engine.getStencilBuffer();
  18924. var renderhighlights = false;
  18925. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18926. this._intermediateRendering = true;
  18927. for (var i = 0; i < this.highlightLayers.length; i++) {
  18928. var highlightLayer = this.highlightLayers[i];
  18929. if (highlightLayer.shouldRender() &&
  18930. (!highlightLayer.camera ||
  18931. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18932. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18933. renderhighlights = true;
  18934. var renderTarget = highlightLayer._mainTexture;
  18935. if (renderTarget._shouldRender()) {
  18936. this._renderId++;
  18937. renderTarget.render(false, false);
  18938. needsRestoreFrameBuffer = true;
  18939. }
  18940. }
  18941. }
  18942. this._intermediateRendering = false;
  18943. this._renderId++;
  18944. }
  18945. if (needsRestoreFrameBuffer) {
  18946. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18947. }
  18948. this._renderTargetsDuration.endMonitoring(false);
  18949. // Prepare Frame
  18950. this.postProcessManager._prepareFrame();
  18951. this._renderDuration.beginMonitoring();
  18952. // Backgrounds
  18953. var layerIndex;
  18954. var layer;
  18955. if (this.layers.length) {
  18956. engine.setDepthBuffer(false);
  18957. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18958. layer = this.layers[layerIndex];
  18959. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18960. layer.render();
  18961. }
  18962. }
  18963. engine.setDepthBuffer(true);
  18964. }
  18965. // Render
  18966. BABYLON.Tools.StartPerformanceCounter("Main render");
  18967. // Activate HighlightLayer stencil
  18968. if (renderhighlights) {
  18969. this._engine.setStencilBuffer(true);
  18970. }
  18971. this._renderingManager.render(null, null, true, true);
  18972. // Restore HighlightLayer stencil
  18973. if (renderhighlights) {
  18974. this._engine.setStencilBuffer(stencilState);
  18975. }
  18976. BABYLON.Tools.EndPerformanceCounter("Main render");
  18977. // Bounding boxes
  18978. if (this._boundingBoxRenderer) {
  18979. this._boundingBoxRenderer.render();
  18980. }
  18981. // Lens flares
  18982. if (this.lensFlaresEnabled) {
  18983. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18984. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18985. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18986. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18987. lensFlareSystem.render();
  18988. }
  18989. }
  18990. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18991. }
  18992. // Foregrounds
  18993. if (this.layers.length) {
  18994. engine.setDepthBuffer(false);
  18995. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18996. layer = this.layers[layerIndex];
  18997. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18998. layer.render();
  18999. }
  19000. }
  19001. engine.setDepthBuffer(true);
  19002. }
  19003. // Highlight Layer
  19004. if (renderhighlights) {
  19005. engine.setDepthBuffer(false);
  19006. for (var i = 0; i < this.highlightLayers.length; i++) {
  19007. if (this.highlightLayers[i].shouldRender()) {
  19008. this.highlightLayers[i].render();
  19009. }
  19010. }
  19011. engine.setDepthBuffer(true);
  19012. }
  19013. this._renderDuration.endMonitoring(false);
  19014. // Finalize frame
  19015. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19016. // Reset some special arrays
  19017. this._renderTargets.reset();
  19018. this._alternateRendering = false;
  19019. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19020. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19021. };
  19022. Scene.prototype._processSubCameras = function (camera) {
  19023. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19024. this._renderForCamera(camera);
  19025. return;
  19026. }
  19027. // Update camera
  19028. this.activeCamera.update();
  19029. // rig cameras
  19030. for (var index = 0; index < camera._rigCameras.length; index++) {
  19031. this._renderForCamera(camera._rigCameras[index]);
  19032. }
  19033. this.activeCamera = camera;
  19034. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19035. };
  19036. Scene.prototype._checkIntersections = function () {
  19037. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19038. var sourceMesh = this._meshesForIntersections.data[index];
  19039. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19040. var action = sourceMesh.actionManager.actions[actionIndex];
  19041. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19042. var parameters = action.getTriggerParameter();
  19043. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19044. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19045. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19046. if (areIntersecting && currentIntersectionInProgress === -1) {
  19047. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19048. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19049. sourceMesh._intersectionsInProgress.push(otherMesh);
  19050. }
  19051. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19052. sourceMesh._intersectionsInProgress.push(otherMesh);
  19053. }
  19054. }
  19055. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19056. //They intersected, and now they don't.
  19057. //is this trigger an exit trigger? execute an event.
  19058. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19059. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19060. }
  19061. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19062. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19063. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19064. }
  19065. }
  19066. }
  19067. }
  19068. }
  19069. };
  19070. Scene.prototype.render = function () {
  19071. if (this.isDisposed) {
  19072. return;
  19073. }
  19074. this._interFrameDuration.endMonitoring();
  19075. this._lastFrameDuration.beginMonitoring();
  19076. this._particlesDuration.fetchNewFrame();
  19077. this._spritesDuration.fetchNewFrame();
  19078. this._activeParticles.fetchNewFrame();
  19079. this._renderDuration.fetchNewFrame();
  19080. this._renderTargetsDuration.fetchNewFrame();
  19081. this._evaluateActiveMeshesDuration.fetchNewFrame();
  19082. this._totalVertices.fetchNewFrame();
  19083. this._activeIndices.fetchNewFrame();
  19084. this._activeBones.fetchNewFrame();
  19085. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  19086. this._meshesForIntersections.reset();
  19087. this.resetCachedMaterial();
  19088. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  19089. // Actions
  19090. if (this.actionManager) {
  19091. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  19092. }
  19093. //Simplification Queue
  19094. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19095. this.simplificationQueue.executeNext();
  19096. }
  19097. if (this._engine.isDeterministicLockStep()) {
  19098. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  19099. var defaultTimeStep = (60.0 / 1000.0);
  19100. if (this._physicsEngine) {
  19101. defaultTimeStep = this._physicsEngine.getTimeStep();
  19102. }
  19103. var maxSubSteps = this._engine.getLockstepMaxSteps();
  19104. this._timeAccumulator += deltaTime;
  19105. // compute the amount of fixed steps we should have taken since the last step
  19106. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  19107. internalSteps = Math.min(internalSteps, maxSubSteps);
  19108. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  19109. this.onBeforeStepObservable.notifyObservers(this);
  19110. // Animations
  19111. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  19112. this._animate();
  19113. // Physics
  19114. if (this._physicsEngine) {
  19115. BABYLON.Tools.StartPerformanceCounter("Physics");
  19116. this._physicsEngine._step(defaultTimeStep);
  19117. BABYLON.Tools.EndPerformanceCounter("Physics");
  19118. }
  19119. this._timeAccumulator -= defaultTimeStep;
  19120. this.onAfterStepObservable.notifyObservers(this);
  19121. this._currentStepId++;
  19122. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  19123. this._evaluateActiveMeshes();
  19124. }
  19125. }
  19126. }
  19127. else {
  19128. // Animations
  19129. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19130. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19131. this._animate();
  19132. // Physics
  19133. if (this._physicsEngine) {
  19134. BABYLON.Tools.StartPerformanceCounter("Physics");
  19135. this._physicsEngine._step(deltaTime / 1000.0);
  19136. BABYLON.Tools.EndPerformanceCounter("Physics");
  19137. }
  19138. }
  19139. // Before render
  19140. this.onBeforeRenderObservable.notifyObservers(this);
  19141. // Customs render targets
  19142. this._renderTargetsDuration.beginMonitoring();
  19143. var beforeRenderTargetDate = BABYLON.Tools.Now;
  19144. var engine = this.getEngine();
  19145. var currentActiveCamera = this.activeCamera;
  19146. if (this.renderTargetsEnabled) {
  19147. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19148. this._intermediateRendering = true;
  19149. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19150. var renderTarget = this.customRenderTargets[customIndex];
  19151. if (renderTarget._shouldRender()) {
  19152. this._renderId++;
  19153. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19154. if (!this.activeCamera)
  19155. throw new Error("Active camera not set");
  19156. // Viewport
  19157. engine.setViewport(this.activeCamera.viewport);
  19158. // Camera
  19159. this.updateTransformMatrix();
  19160. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19161. }
  19162. }
  19163. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19164. this._intermediateRendering = false;
  19165. this._renderId++;
  19166. }
  19167. // Restore back buffer
  19168. if (this.customRenderTargets.length > 0) {
  19169. engine.restoreDefaultFramebuffer();
  19170. }
  19171. this._renderTargetsDuration.endMonitoring();
  19172. this.activeCamera = currentActiveCamera;
  19173. // Procedural textures
  19174. if (this.proceduralTexturesEnabled) {
  19175. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19176. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19177. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19178. if (proceduralTexture._shouldRender()) {
  19179. proceduralTexture.render();
  19180. }
  19181. }
  19182. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19183. }
  19184. // Clear
  19185. if (this.autoClearDepthAndStencil || this.autoClear) {
  19186. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  19187. }
  19188. // Shadows
  19189. if (this.shadowsEnabled) {
  19190. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19191. var light = this.lights[lightIndex];
  19192. var shadowGenerator = light.getShadowGenerator();
  19193. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  19194. var shadowMap = shadowGenerator.getShadowMap();
  19195. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  19196. this._renderTargets.push(shadowMap);
  19197. }
  19198. }
  19199. }
  19200. }
  19201. // Depth renderer
  19202. if (this._depthRenderer) {
  19203. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19204. }
  19205. // Geometry renderer
  19206. if (this._geometryBufferRenderer) {
  19207. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  19208. }
  19209. // RenderPipeline
  19210. if (this._postProcessRenderPipelineManager) {
  19211. this._postProcessRenderPipelineManager.update();
  19212. }
  19213. // Multi-cameras?
  19214. if (this.activeCameras.length > 0) {
  19215. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19216. if (cameraIndex > 0) {
  19217. this._engine.clear(null, false, true, true);
  19218. }
  19219. this._processSubCameras(this.activeCameras[cameraIndex]);
  19220. }
  19221. }
  19222. else {
  19223. if (!this.activeCamera) {
  19224. throw new Error("No camera defined");
  19225. }
  19226. this._processSubCameras(this.activeCamera);
  19227. }
  19228. // Intersection checks
  19229. this._checkIntersections();
  19230. // Update the audio listener attached to the camera
  19231. if (BABYLON.AudioEngine) {
  19232. this._updateAudioParameters();
  19233. }
  19234. // After render
  19235. if (this.afterRender) {
  19236. this.afterRender();
  19237. }
  19238. this.onAfterRenderObservable.notifyObservers(this);
  19239. // Cleaning
  19240. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19241. this._toBeDisposed.data[index].dispose();
  19242. this._toBeDisposed[index] = null;
  19243. }
  19244. this._toBeDisposed.reset();
  19245. if (this.dumpNextRenderTargets) {
  19246. this.dumpNextRenderTargets = false;
  19247. }
  19248. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19249. this._interFrameDuration.beginMonitoring();
  19250. this._lastFrameDuration.endMonitoring();
  19251. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19252. this._totalLightsCounter.addCount(this.lights.length, true);
  19253. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19254. this._totalTexturesCounter.addCount(this.textures.length, true);
  19255. this._activeBones.addCount(0, true);
  19256. this._activeIndices.addCount(0, true);
  19257. this._activeParticles.addCount(0, true);
  19258. };
  19259. Scene.prototype._updateAudioParameters = function () {
  19260. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19261. return;
  19262. }
  19263. var listeningCamera;
  19264. var audioEngine = BABYLON.Engine.audioEngine;
  19265. if (this.activeCameras.length > 0) {
  19266. listeningCamera = this.activeCameras[0];
  19267. }
  19268. else {
  19269. listeningCamera = this.activeCamera;
  19270. }
  19271. if (listeningCamera && audioEngine.canUseWebAudio) {
  19272. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19273. // for VR cameras
  19274. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  19275. listeningCamera = listeningCamera.rigCameras[0];
  19276. }
  19277. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19278. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19279. cameraDirection.normalize();
  19280. // To avoid some errors on GearVR
  19281. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  19282. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19283. }
  19284. var i;
  19285. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19286. var sound = this.mainSoundTrack.soundCollection[i];
  19287. if (sound.useCustomAttenuation) {
  19288. sound.updateDistanceFromListener();
  19289. }
  19290. }
  19291. for (i = 0; i < this.soundTracks.length; i++) {
  19292. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19293. sound = this.soundTracks[i].soundCollection[j];
  19294. if (sound.useCustomAttenuation) {
  19295. sound.updateDistanceFromListener();
  19296. }
  19297. }
  19298. }
  19299. }
  19300. };
  19301. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19302. // Audio
  19303. get: function () {
  19304. return this._audioEnabled;
  19305. },
  19306. set: function (value) {
  19307. this._audioEnabled = value;
  19308. if (BABYLON.AudioEngine) {
  19309. if (this._audioEnabled) {
  19310. this._enableAudio();
  19311. }
  19312. else {
  19313. this._disableAudio();
  19314. }
  19315. }
  19316. },
  19317. enumerable: true,
  19318. configurable: true
  19319. });
  19320. Scene.prototype._disableAudio = function () {
  19321. var i;
  19322. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19323. this.mainSoundTrack.soundCollection[i].pause();
  19324. }
  19325. for (i = 0; i < this.soundTracks.length; i++) {
  19326. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19327. this.soundTracks[i].soundCollection[j].pause();
  19328. }
  19329. }
  19330. };
  19331. Scene.prototype._enableAudio = function () {
  19332. var i;
  19333. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19334. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19335. this.mainSoundTrack.soundCollection[i].play();
  19336. }
  19337. }
  19338. for (i = 0; i < this.soundTracks.length; i++) {
  19339. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19340. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19341. this.soundTracks[i].soundCollection[j].play();
  19342. }
  19343. }
  19344. }
  19345. };
  19346. Object.defineProperty(Scene.prototype, "headphone", {
  19347. get: function () {
  19348. return this._headphone;
  19349. },
  19350. set: function (value) {
  19351. this._headphone = value;
  19352. if (BABYLON.AudioEngine) {
  19353. if (this._headphone) {
  19354. this._switchAudioModeForHeadphones();
  19355. }
  19356. else {
  19357. this._switchAudioModeForNormalSpeakers();
  19358. }
  19359. }
  19360. },
  19361. enumerable: true,
  19362. configurable: true
  19363. });
  19364. Scene.prototype._switchAudioModeForHeadphones = function () {
  19365. this.mainSoundTrack.switchPanningModelToHRTF();
  19366. for (var i = 0; i < this.soundTracks.length; i++) {
  19367. this.soundTracks[i].switchPanningModelToHRTF();
  19368. }
  19369. };
  19370. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19371. this.mainSoundTrack.switchPanningModelToEqualPower();
  19372. for (var i = 0; i < this.soundTracks.length; i++) {
  19373. this.soundTracks[i].switchPanningModelToEqualPower();
  19374. }
  19375. };
  19376. Scene.prototype.enableDepthRenderer = function () {
  19377. if (this._depthRenderer) {
  19378. return this._depthRenderer;
  19379. }
  19380. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19381. return this._depthRenderer;
  19382. };
  19383. Scene.prototype.disableDepthRenderer = function () {
  19384. if (!this._depthRenderer) {
  19385. return;
  19386. }
  19387. this._depthRenderer.dispose();
  19388. this._depthRenderer = null;
  19389. };
  19390. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  19391. if (ratio === void 0) { ratio = 1; }
  19392. if (this._geometryBufferRenderer) {
  19393. return this._geometryBufferRenderer;
  19394. }
  19395. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  19396. if (!this._geometryBufferRenderer.isSupported) {
  19397. this._geometryBufferRenderer = null;
  19398. }
  19399. return this._geometryBufferRenderer;
  19400. };
  19401. Scene.prototype.disableGeometryBufferRenderer = function () {
  19402. if (!this._geometryBufferRenderer) {
  19403. return;
  19404. }
  19405. this._geometryBufferRenderer.dispose();
  19406. this._geometryBufferRenderer = null;
  19407. };
  19408. Scene.prototype.freezeMaterials = function () {
  19409. for (var i = 0; i < this.materials.length; i++) {
  19410. this.materials[i].freeze();
  19411. }
  19412. };
  19413. Scene.prototype.unfreezeMaterials = function () {
  19414. for (var i = 0; i < this.materials.length; i++) {
  19415. this.materials[i].unfreeze();
  19416. }
  19417. };
  19418. Scene.prototype.dispose = function () {
  19419. this.beforeRender = null;
  19420. this.afterRender = null;
  19421. this.skeletons = [];
  19422. this.morphTargetManagers = [];
  19423. this.importedMeshesFiles = new Array();
  19424. this.resetCachedMaterial();
  19425. if (this._depthRenderer) {
  19426. this._depthRenderer.dispose();
  19427. }
  19428. if (this._gamepadManager) {
  19429. this._gamepadManager.dispose();
  19430. this._gamepadManager = null;
  19431. }
  19432. // Smart arrays
  19433. if (this.activeCamera) {
  19434. this.activeCamera._activeMeshes.dispose();
  19435. this.activeCamera = null;
  19436. }
  19437. this._activeMeshes.dispose();
  19438. this._renderingManager.dispose();
  19439. this._processedMaterials.dispose();
  19440. this._activeParticleSystems.dispose();
  19441. this._activeSkeletons.dispose();
  19442. this._softwareSkinnedMeshes.dispose();
  19443. this._renderTargets.dispose();
  19444. if (this._boundingBoxRenderer) {
  19445. this._boundingBoxRenderer.dispose();
  19446. }
  19447. this._meshesForIntersections.dispose();
  19448. this._toBeDisposed.dispose();
  19449. // Debug layer
  19450. if (this._debugLayer) {
  19451. this._debugLayer.hide();
  19452. }
  19453. // Events
  19454. this.onDisposeObservable.notifyObservers(this);
  19455. this.onDisposeObservable.clear();
  19456. this.onBeforeRenderObservable.clear();
  19457. this.onAfterRenderObservable.clear();
  19458. this.detachControl();
  19459. // Release sounds & sounds tracks
  19460. if (BABYLON.AudioEngine) {
  19461. this.disposeSounds();
  19462. }
  19463. // VR Helper
  19464. if (this.VRHelper) {
  19465. this.VRHelper.dispose();
  19466. }
  19467. // Detach cameras
  19468. var canvas = this._engine.getRenderingCanvas();
  19469. var index;
  19470. for (index = 0; index < this.cameras.length; index++) {
  19471. this.cameras[index].detachControl(canvas);
  19472. }
  19473. // Release lights
  19474. while (this.lights.length) {
  19475. this.lights[0].dispose();
  19476. }
  19477. // Release meshes
  19478. while (this.meshes.length) {
  19479. this.meshes[0].dispose(true);
  19480. }
  19481. // Release cameras
  19482. while (this.cameras.length) {
  19483. this.cameras[0].dispose();
  19484. }
  19485. // Release materials
  19486. if (this.defaultMaterial) {
  19487. this.defaultMaterial.dispose();
  19488. }
  19489. while (this.multiMaterials.length) {
  19490. this.multiMaterials[0].dispose();
  19491. }
  19492. while (this.materials.length) {
  19493. this.materials[0].dispose();
  19494. }
  19495. // Release particles
  19496. while (this.particleSystems.length) {
  19497. this.particleSystems[0].dispose();
  19498. }
  19499. // Release sprites
  19500. while (this.spriteManagers.length) {
  19501. this.spriteManagers[0].dispose();
  19502. }
  19503. // Release postProcesses
  19504. while (this.postProcesses.length) {
  19505. this.postProcesses[0].dispose();
  19506. }
  19507. // Release layers
  19508. while (this.layers.length) {
  19509. this.layers[0].dispose();
  19510. }
  19511. while (this.highlightLayers.length) {
  19512. this.highlightLayers[0].dispose();
  19513. }
  19514. // Release textures
  19515. while (this.textures.length) {
  19516. this.textures[0].dispose();
  19517. }
  19518. // Release UBO
  19519. this._sceneUbo.dispose();
  19520. if (this._alternateSceneUbo) {
  19521. this._alternateSceneUbo.dispose();
  19522. }
  19523. // Post-processes
  19524. this.postProcessManager.dispose();
  19525. if (this._postProcessRenderPipelineManager) {
  19526. this._postProcessRenderPipelineManager.dispose();
  19527. }
  19528. // Physics
  19529. if (this._physicsEngine) {
  19530. this.disablePhysicsEngine();
  19531. }
  19532. // Remove from engine
  19533. index = this._engine.scenes.indexOf(this);
  19534. if (index > -1) {
  19535. this._engine.scenes.splice(index, 1);
  19536. }
  19537. this._engine.wipeCaches();
  19538. this._engine = null;
  19539. this.defaultMaterial = null;
  19540. this.multiMaterials = null;
  19541. this.materials = null;
  19542. };
  19543. Object.defineProperty(Scene.prototype, "isDisposed", {
  19544. get: function () {
  19545. return !this._engine;
  19546. },
  19547. enumerable: true,
  19548. configurable: true
  19549. });
  19550. // Release sounds & sounds tracks
  19551. Scene.prototype.disposeSounds = function () {
  19552. if (!this._mainSoundTrack) {
  19553. return;
  19554. }
  19555. this.mainSoundTrack.dispose();
  19556. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19557. this.soundTracks[scIndex].dispose();
  19558. }
  19559. };
  19560. // Octrees
  19561. Scene.prototype.getWorldExtends = function () {
  19562. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19563. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19564. for (var index = 0; index < this.meshes.length; index++) {
  19565. var mesh = this.meshes[index];
  19566. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19567. continue;
  19568. }
  19569. mesh.computeWorldMatrix(true);
  19570. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19571. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19572. BABYLON.Tools.CheckExtends(minBox, min, max);
  19573. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19574. }
  19575. return {
  19576. min: min,
  19577. max: max
  19578. };
  19579. };
  19580. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19581. if (maxCapacity === void 0) { maxCapacity = 64; }
  19582. if (maxDepth === void 0) { maxDepth = 2; }
  19583. if (!this._selectionOctree) {
  19584. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19585. }
  19586. var worldExtends = this.getWorldExtends();
  19587. // Update octree
  19588. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19589. return this._selectionOctree;
  19590. };
  19591. // Picking
  19592. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19593. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19594. var engine = this._engine;
  19595. if (!camera) {
  19596. if (!this.activeCamera)
  19597. throw new Error("Active camera not set");
  19598. camera = this.activeCamera;
  19599. }
  19600. var cameraViewport = camera.viewport;
  19601. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19602. // Moving coordinates to local viewport world
  19603. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19604. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19605. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19606. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19607. };
  19608. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19609. if (!BABYLON.PickingInfo) {
  19610. return null;
  19611. }
  19612. var engine = this._engine;
  19613. if (!camera) {
  19614. if (!this.activeCamera)
  19615. throw new Error("Active camera not set");
  19616. camera = this.activeCamera;
  19617. }
  19618. var cameraViewport = camera.viewport;
  19619. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19620. var identity = BABYLON.Matrix.Identity();
  19621. // Moving coordinates to local viewport world
  19622. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19623. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19624. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19625. };
  19626. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19627. if (!BABYLON.PickingInfo) {
  19628. return null;
  19629. }
  19630. var pickingInfo = null;
  19631. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19632. var mesh = this.meshes[meshIndex];
  19633. if (predicate) {
  19634. if (!predicate(mesh)) {
  19635. continue;
  19636. }
  19637. }
  19638. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19639. continue;
  19640. }
  19641. var world = mesh.getWorldMatrix();
  19642. var ray = rayFunction(world);
  19643. var result = mesh.intersects(ray, fastCheck);
  19644. if (!result || !result.hit)
  19645. continue;
  19646. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19647. continue;
  19648. pickingInfo = result;
  19649. if (fastCheck) {
  19650. break;
  19651. }
  19652. }
  19653. return pickingInfo || new BABYLON.PickingInfo();
  19654. };
  19655. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19656. if (!BABYLON.PickingInfo) {
  19657. return null;
  19658. }
  19659. var pickingInfos = new Array();
  19660. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19661. var mesh = this.meshes[meshIndex];
  19662. if (predicate) {
  19663. if (!predicate(mesh)) {
  19664. continue;
  19665. }
  19666. }
  19667. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19668. continue;
  19669. }
  19670. var world = mesh.getWorldMatrix();
  19671. var ray = rayFunction(world);
  19672. var result = mesh.intersects(ray, false);
  19673. if (!result || !result.hit)
  19674. continue;
  19675. pickingInfos.push(result);
  19676. }
  19677. return pickingInfos;
  19678. };
  19679. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19680. if (!BABYLON.PickingInfo) {
  19681. return null;
  19682. }
  19683. var pickingInfo = null;
  19684. camera = camera || this.activeCamera;
  19685. if (this.spriteManagers.length > 0) {
  19686. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19687. var spriteManager = this.spriteManagers[spriteIndex];
  19688. if (!spriteManager.isPickable) {
  19689. continue;
  19690. }
  19691. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19692. if (!result || !result.hit)
  19693. continue;
  19694. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19695. continue;
  19696. pickingInfo = result;
  19697. if (fastCheck) {
  19698. break;
  19699. }
  19700. }
  19701. }
  19702. return pickingInfo || new BABYLON.PickingInfo();
  19703. };
  19704. /** Launch a ray to try to pick a mesh in the scene
  19705. * @param x position on screen
  19706. * @param y position on screen
  19707. * @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
  19708. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19709. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19710. */
  19711. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19712. var _this = this;
  19713. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19714. };
  19715. /** Launch a ray to try to pick a sprite in the scene
  19716. * @param x position on screen
  19717. * @param y position on screen
  19718. * @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
  19719. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19720. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19721. */
  19722. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19723. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19724. };
  19725. /** Use the given ray to pick a mesh in the scene
  19726. * @param ray The ray to use to pick meshes
  19727. * @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
  19728. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19729. */
  19730. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19731. var _this = this;
  19732. return this._internalPick(function (world) {
  19733. if (!_this._pickWithRayInverseMatrix) {
  19734. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19735. }
  19736. world.invertToRef(_this._pickWithRayInverseMatrix);
  19737. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19738. }, predicate, fastCheck);
  19739. };
  19740. /**
  19741. * Launch a ray to try to pick a mesh in the scene
  19742. * @param x X position on screen
  19743. * @param y Y position on screen
  19744. * @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
  19745. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19746. */
  19747. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19748. var _this = this;
  19749. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19750. };
  19751. /**
  19752. * Launch a ray to try to pick a mesh in the scene
  19753. * @param ray Ray to use
  19754. * @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
  19755. */
  19756. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19757. var _this = this;
  19758. return this._internalMultiPick(function (world) {
  19759. if (!_this._pickWithRayInverseMatrix) {
  19760. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19761. }
  19762. world.invertToRef(_this._pickWithRayInverseMatrix);
  19763. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19764. }, predicate);
  19765. };
  19766. Scene.prototype.setPointerOverMesh = function (mesh) {
  19767. if (this._pointerOverMesh === mesh) {
  19768. return;
  19769. }
  19770. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19771. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19772. }
  19773. this._pointerOverMesh = mesh;
  19774. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19775. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19776. }
  19777. };
  19778. Scene.prototype.getPointerOverMesh = function () {
  19779. return this._pointerOverMesh;
  19780. };
  19781. Scene.prototype.setPointerOverSprite = function (sprite) {
  19782. if (this._pointerOverSprite === sprite) {
  19783. return;
  19784. }
  19785. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19786. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19787. }
  19788. this._pointerOverSprite = sprite;
  19789. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19790. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19791. }
  19792. };
  19793. Scene.prototype.getPointerOverSprite = function () {
  19794. return this._pointerOverSprite;
  19795. };
  19796. // Physics
  19797. Scene.prototype.getPhysicsEngine = function () {
  19798. return this._physicsEngine;
  19799. };
  19800. /**
  19801. * Enables physics to the current scene
  19802. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19803. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19804. * @return {boolean} was the physics engine initialized
  19805. */
  19806. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19807. if (this._physicsEngine) {
  19808. return true;
  19809. }
  19810. try {
  19811. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19812. return true;
  19813. }
  19814. catch (e) {
  19815. BABYLON.Tools.Error(e.message);
  19816. return false;
  19817. }
  19818. };
  19819. Scene.prototype.disablePhysicsEngine = function () {
  19820. if (!this._physicsEngine) {
  19821. return;
  19822. }
  19823. this._physicsEngine.dispose();
  19824. this._physicsEngine = undefined;
  19825. };
  19826. Scene.prototype.isPhysicsEnabled = function () {
  19827. return this._physicsEngine !== undefined;
  19828. };
  19829. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19830. var mesh = compound.parts[0].mesh;
  19831. mesh.physicsImpostor.dispose();
  19832. mesh.physicsImpostor = null;
  19833. };
  19834. // Misc.
  19835. Scene.prototype._rebuildGeometries = function () {
  19836. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19837. var geometry = _a[_i];
  19838. geometry._rebuild();
  19839. }
  19840. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19841. var mesh = _c[_b];
  19842. mesh._rebuild();
  19843. }
  19844. if (this.postProcessManager) {
  19845. this.postProcessManager._rebuild();
  19846. }
  19847. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19848. var layer = _e[_d];
  19849. layer._rebuild();
  19850. }
  19851. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19852. var highlightLayer = _g[_f];
  19853. highlightLayer._rebuild();
  19854. }
  19855. if (this._boundingBoxRenderer) {
  19856. this._boundingBoxRenderer._rebuild();
  19857. }
  19858. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  19859. var system = _j[_h];
  19860. system.rebuild();
  19861. }
  19862. if (this._postProcessRenderPipelineManager) {
  19863. this._postProcessRenderPipelineManager._rebuild();
  19864. }
  19865. };
  19866. Scene.prototype._rebuildTextures = function () {
  19867. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19868. var texture = _a[_i];
  19869. texture._rebuild();
  19870. }
  19871. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19872. };
  19873. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19874. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19875. if (replace === void 0) { replace = false; }
  19876. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19877. // Dispose existing camera or light in replace mode.
  19878. if (replace) {
  19879. if (this.activeCamera) {
  19880. this.activeCamera.dispose();
  19881. this.activeCamera = null;
  19882. }
  19883. if (this.lights) {
  19884. for (var i = 0; i < this.lights.length; i++) {
  19885. this.lights[i].dispose();
  19886. }
  19887. }
  19888. }
  19889. // Light
  19890. if (this.lights.length === 0) {
  19891. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19892. }
  19893. // Camera
  19894. if (!this.activeCamera) {
  19895. var worldExtends = this.getWorldExtends();
  19896. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19897. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19898. var camera;
  19899. var radius = worldSize.length() * 1.5;
  19900. if (createArcRotateCamera) {
  19901. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19902. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19903. arcRotateCamera.wheelPrecision = 100 / radius;
  19904. camera = arcRotateCamera;
  19905. }
  19906. else {
  19907. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19908. freeCamera.setTarget(worldCenter);
  19909. camera = freeCamera;
  19910. }
  19911. camera.minZ = radius * 0.01;
  19912. camera.maxZ = radius * 100;
  19913. camera.speed = radius * 0.2;
  19914. this.activeCamera = camera;
  19915. if (attachCameraControls) {
  19916. camera.attachControl(this.getEngine().getRenderingCanvas());
  19917. }
  19918. }
  19919. };
  19920. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19921. if (pbr === void 0) { pbr = false; }
  19922. if (scale === void 0) { scale = 1000; }
  19923. if (blur === void 0) { blur = 0; }
  19924. if (environmentTexture) {
  19925. this.environmentTexture = environmentTexture;
  19926. }
  19927. if (!this.environmentTexture) {
  19928. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19929. return;
  19930. }
  19931. // Skybox
  19932. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19933. if (pbr) {
  19934. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19935. hdrSkyboxMaterial.backFaceCulling = false;
  19936. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19937. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19938. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19939. hdrSkyboxMaterial.disableLighting = true;
  19940. hdrSkyboxMaterial.twoSidedLighting = true;
  19941. hdrSkybox.infiniteDistance = true;
  19942. hdrSkybox.material = hdrSkyboxMaterial;
  19943. }
  19944. else {
  19945. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19946. skyboxMaterial.backFaceCulling = false;
  19947. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19948. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19949. skyboxMaterial.disableLighting = true;
  19950. hdrSkybox.infiniteDistance = true;
  19951. hdrSkybox.material = skyboxMaterial;
  19952. }
  19953. return hdrSkybox;
  19954. };
  19955. Scene.prototype.createDefaultVRExperience = function () {
  19956. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19957. };
  19958. // Tags
  19959. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19960. if (tagsQuery === undefined) {
  19961. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19962. return list;
  19963. }
  19964. var listByTags = [];
  19965. forEach = forEach || (function (item) { return; });
  19966. for (var i in list) {
  19967. var item = list[i];
  19968. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19969. listByTags.push(item);
  19970. forEach(item);
  19971. }
  19972. }
  19973. return listByTags;
  19974. };
  19975. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19976. return this._getByTags(this.meshes, tagsQuery, forEach);
  19977. };
  19978. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19979. return this._getByTags(this.cameras, tagsQuery, forEach);
  19980. };
  19981. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19982. return this._getByTags(this.lights, tagsQuery, forEach);
  19983. };
  19984. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19985. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19986. };
  19987. /**
  19988. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19989. * This allowed control for front to back rendering or reversly depending of the special needs.
  19990. *
  19991. * @param renderingGroupId The rendering group id corresponding to its index
  19992. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19993. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19994. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19995. */
  19996. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19997. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19998. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19999. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20000. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20001. };
  20002. /**
  20003. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20004. *
  20005. * @param renderingGroupId The rendering group id corresponding to its index
  20006. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20007. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20008. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20009. */
  20010. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20011. if (depth === void 0) { depth = true; }
  20012. if (stencil === void 0) { stencil = true; }
  20013. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20014. };
  20015. /**
  20016. * Will flag all materials as dirty to trigger new shader compilation
  20017. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20018. */
  20019. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20020. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20021. var material = _a[_i];
  20022. if (predicate && !predicate(material)) {
  20023. continue;
  20024. }
  20025. material.markAsDirty(flag);
  20026. }
  20027. };
  20028. return Scene;
  20029. }());
  20030. // Statics
  20031. Scene._FOGMODE_NONE = 0;
  20032. Scene._FOGMODE_EXP = 1;
  20033. Scene._FOGMODE_EXP2 = 2;
  20034. Scene._FOGMODE_LINEAR = 3;
  20035. Scene.MinDeltaTime = 1.0;
  20036. Scene.MaxDeltaTime = 1000.0;
  20037. /** The distance in pixel that you have to move to prevent some events */
  20038. Scene.DragMovementThreshold = 10; // in pixels
  20039. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  20040. Scene.LongPressDelay = 500; // in milliseconds
  20041. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  20042. Scene.DoubleClickDelay = 300; // in milliseconds
  20043. /** If you need to check double click without raising a single click at first click, enable this flag */
  20044. Scene.ExclusiveDoubleClickMode = false;
  20045. BABYLON.Scene = Scene;
  20046. })(BABYLON || (BABYLON = {}));
  20047. //# sourceMappingURL=babylon.scene.js.map
  20048. var BABYLON;
  20049. (function (BABYLON) {
  20050. var Buffer = (function () {
  20051. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  20052. if (engine instanceof BABYLON.Mesh) {
  20053. this._engine = engine.getScene().getEngine();
  20054. }
  20055. else {
  20056. this._engine = engine;
  20057. }
  20058. this._updatable = updatable;
  20059. this._data = data;
  20060. this._strideSize = stride;
  20061. if (!postponeInternalCreation) {
  20062. this.create();
  20063. }
  20064. this._instanced = instanced;
  20065. this._instanceDivisor = instanced ? 1 : 0;
  20066. }
  20067. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  20068. // a lot of these parameters are ignored as they are overriden by the buffer
  20069. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  20070. };
  20071. // Properties
  20072. Buffer.prototype.isUpdatable = function () {
  20073. return this._updatable;
  20074. };
  20075. Buffer.prototype.getData = function () {
  20076. return this._data;
  20077. };
  20078. Buffer.prototype.getBuffer = function () {
  20079. return this._buffer;
  20080. };
  20081. Buffer.prototype.getStrideSize = function () {
  20082. return this._strideSize;
  20083. };
  20084. Buffer.prototype.getIsInstanced = function () {
  20085. return this._instanced;
  20086. };
  20087. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  20088. get: function () {
  20089. return this._instanceDivisor;
  20090. },
  20091. set: function (value) {
  20092. this._instanceDivisor = value;
  20093. if (value == 0) {
  20094. this._instanced = false;
  20095. }
  20096. else {
  20097. this._instanced = true;
  20098. }
  20099. },
  20100. enumerable: true,
  20101. configurable: true
  20102. });
  20103. // Methods
  20104. Buffer.prototype.create = function (data) {
  20105. if (!data && this._buffer) {
  20106. return; // nothing to do
  20107. }
  20108. data = data || this._data;
  20109. if (!this._buffer) {
  20110. if (this._updatable) {
  20111. this._buffer = this._engine.createDynamicVertexBuffer(data);
  20112. this._data = data;
  20113. }
  20114. else {
  20115. this._buffer = this._engine.createVertexBuffer(data);
  20116. }
  20117. }
  20118. else if (this._updatable) {
  20119. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  20120. this._data = data;
  20121. }
  20122. };
  20123. Buffer.prototype._rebuild = function () {
  20124. this._buffer = null;
  20125. this.create(this._data);
  20126. };
  20127. Buffer.prototype.update = function (data) {
  20128. this.create(data);
  20129. };
  20130. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  20131. if (!this._buffer) {
  20132. return;
  20133. }
  20134. if (this._updatable) {
  20135. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  20136. this._data = null;
  20137. }
  20138. };
  20139. Buffer.prototype.dispose = function () {
  20140. if (!this._buffer) {
  20141. return;
  20142. }
  20143. if (this._engine._releaseBuffer(this._buffer)) {
  20144. this._buffer = null;
  20145. }
  20146. };
  20147. return Buffer;
  20148. }());
  20149. BABYLON.Buffer = Buffer;
  20150. })(BABYLON || (BABYLON = {}));
  20151. //# sourceMappingURL=babylon.buffer.js.map
  20152. var BABYLON;
  20153. (function (BABYLON) {
  20154. var VertexBuffer = (function () {
  20155. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  20156. if (!stride) {
  20157. // Deduce stride from kind
  20158. switch (kind) {
  20159. case VertexBuffer.PositionKind:
  20160. stride = 3;
  20161. break;
  20162. case VertexBuffer.NormalKind:
  20163. stride = 3;
  20164. break;
  20165. case VertexBuffer.UVKind:
  20166. case VertexBuffer.UV2Kind:
  20167. case VertexBuffer.UV3Kind:
  20168. case VertexBuffer.UV4Kind:
  20169. case VertexBuffer.UV5Kind:
  20170. case VertexBuffer.UV6Kind:
  20171. stride = 2;
  20172. break;
  20173. case VertexBuffer.TangentKind:
  20174. case VertexBuffer.ColorKind:
  20175. stride = 4;
  20176. break;
  20177. case VertexBuffer.MatricesIndicesKind:
  20178. case VertexBuffer.MatricesIndicesExtraKind:
  20179. stride = 4;
  20180. break;
  20181. case VertexBuffer.MatricesWeightsKind:
  20182. case VertexBuffer.MatricesWeightsExtraKind:
  20183. stride = 4;
  20184. break;
  20185. }
  20186. }
  20187. if (data instanceof BABYLON.Buffer) {
  20188. if (!stride) {
  20189. stride = data.getStrideSize();
  20190. }
  20191. this._buffer = data;
  20192. this._ownsBuffer = false;
  20193. }
  20194. else {
  20195. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  20196. this._ownsBuffer = true;
  20197. }
  20198. this._stride = stride;
  20199. this._offset = offset ? offset : 0;
  20200. this._size = size ? size : stride;
  20201. this._kind = kind;
  20202. }
  20203. VertexBuffer.prototype._rebuild = function () {
  20204. if (!this._buffer) {
  20205. return;
  20206. }
  20207. this._buffer._rebuild();
  20208. };
  20209. /**
  20210. * Returns the kind of the VertexBuffer (string).
  20211. */
  20212. VertexBuffer.prototype.getKind = function () {
  20213. return this._kind;
  20214. };
  20215. // Properties
  20216. /**
  20217. * Boolean : is the VertexBuffer updatable ?
  20218. */
  20219. VertexBuffer.prototype.isUpdatable = function () {
  20220. return this._buffer.isUpdatable();
  20221. };
  20222. /**
  20223. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  20224. */
  20225. VertexBuffer.prototype.getData = function () {
  20226. return this._buffer.getData();
  20227. };
  20228. /**
  20229. * Returns the WebGLBuffer associated to the VertexBuffer.
  20230. */
  20231. VertexBuffer.prototype.getBuffer = function () {
  20232. return this._buffer.getBuffer();
  20233. };
  20234. /**
  20235. * Returns the stride of the VertexBuffer (integer).
  20236. */
  20237. VertexBuffer.prototype.getStrideSize = function () {
  20238. return this._stride;
  20239. };
  20240. /**
  20241. * Returns the offset (integer).
  20242. */
  20243. VertexBuffer.prototype.getOffset = function () {
  20244. return this._offset;
  20245. };
  20246. /**
  20247. * Returns the VertexBuffer total size (integer).
  20248. */
  20249. VertexBuffer.prototype.getSize = function () {
  20250. return this._size;
  20251. };
  20252. /**
  20253. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  20254. */
  20255. VertexBuffer.prototype.getIsInstanced = function () {
  20256. return this._buffer.getIsInstanced();
  20257. };
  20258. /**
  20259. * Returns the instancing divisor, zero for non-instanced (integer).
  20260. */
  20261. VertexBuffer.prototype.getInstanceDivisor = function () {
  20262. return this._buffer.instanceDivisor;
  20263. };
  20264. // Methods
  20265. /**
  20266. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  20267. * Returns the created WebGLBuffer.
  20268. */
  20269. VertexBuffer.prototype.create = function (data) {
  20270. return this._buffer.create(data);
  20271. };
  20272. /**
  20273. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20274. * Returns the updated WebGLBuffer.
  20275. */
  20276. VertexBuffer.prototype.update = function (data) {
  20277. return this._buffer.update(data);
  20278. };
  20279. /**
  20280. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20281. * Returns the directly updated WebGLBuffer.
  20282. */
  20283. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  20284. return this._buffer.updateDirectly(data, offset);
  20285. };
  20286. /**
  20287. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  20288. */
  20289. VertexBuffer.prototype.dispose = function () {
  20290. if (this._ownsBuffer) {
  20291. this._buffer.dispose();
  20292. }
  20293. };
  20294. Object.defineProperty(VertexBuffer, "PositionKind", {
  20295. get: function () {
  20296. return VertexBuffer._PositionKind;
  20297. },
  20298. enumerable: true,
  20299. configurable: true
  20300. });
  20301. Object.defineProperty(VertexBuffer, "NormalKind", {
  20302. get: function () {
  20303. return VertexBuffer._NormalKind;
  20304. },
  20305. enumerable: true,
  20306. configurable: true
  20307. });
  20308. Object.defineProperty(VertexBuffer, "TangentKind", {
  20309. get: function () {
  20310. return VertexBuffer._TangentKind;
  20311. },
  20312. enumerable: true,
  20313. configurable: true
  20314. });
  20315. Object.defineProperty(VertexBuffer, "UVKind", {
  20316. get: function () {
  20317. return VertexBuffer._UVKind;
  20318. },
  20319. enumerable: true,
  20320. configurable: true
  20321. });
  20322. Object.defineProperty(VertexBuffer, "UV2Kind", {
  20323. get: function () {
  20324. return VertexBuffer._UV2Kind;
  20325. },
  20326. enumerable: true,
  20327. configurable: true
  20328. });
  20329. Object.defineProperty(VertexBuffer, "UV3Kind", {
  20330. get: function () {
  20331. return VertexBuffer._UV3Kind;
  20332. },
  20333. enumerable: true,
  20334. configurable: true
  20335. });
  20336. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20337. get: function () {
  20338. return VertexBuffer._UV4Kind;
  20339. },
  20340. enumerable: true,
  20341. configurable: true
  20342. });
  20343. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20344. get: function () {
  20345. return VertexBuffer._UV5Kind;
  20346. },
  20347. enumerable: true,
  20348. configurable: true
  20349. });
  20350. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20351. get: function () {
  20352. return VertexBuffer._UV6Kind;
  20353. },
  20354. enumerable: true,
  20355. configurable: true
  20356. });
  20357. Object.defineProperty(VertexBuffer, "ColorKind", {
  20358. get: function () {
  20359. return VertexBuffer._ColorKind;
  20360. },
  20361. enumerable: true,
  20362. configurable: true
  20363. });
  20364. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20365. get: function () {
  20366. return VertexBuffer._MatricesIndicesKind;
  20367. },
  20368. enumerable: true,
  20369. configurable: true
  20370. });
  20371. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20372. get: function () {
  20373. return VertexBuffer._MatricesWeightsKind;
  20374. },
  20375. enumerable: true,
  20376. configurable: true
  20377. });
  20378. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20379. get: function () {
  20380. return VertexBuffer._MatricesIndicesExtraKind;
  20381. },
  20382. enumerable: true,
  20383. configurable: true
  20384. });
  20385. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20386. get: function () {
  20387. return VertexBuffer._MatricesWeightsExtraKind;
  20388. },
  20389. enumerable: true,
  20390. configurable: true
  20391. });
  20392. return VertexBuffer;
  20393. }());
  20394. // Enums
  20395. VertexBuffer._PositionKind = "position";
  20396. VertexBuffer._NormalKind = "normal";
  20397. VertexBuffer._TangentKind = "tangent";
  20398. VertexBuffer._UVKind = "uv";
  20399. VertexBuffer._UV2Kind = "uv2";
  20400. VertexBuffer._UV3Kind = "uv3";
  20401. VertexBuffer._UV4Kind = "uv4";
  20402. VertexBuffer._UV5Kind = "uv5";
  20403. VertexBuffer._UV6Kind = "uv6";
  20404. VertexBuffer._ColorKind = "color";
  20405. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20406. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20407. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20408. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20409. BABYLON.VertexBuffer = VertexBuffer;
  20410. })(BABYLON || (BABYLON = {}));
  20411. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20412. var BABYLON;
  20413. (function (BABYLON) {
  20414. var InternalTexture = (function () {
  20415. function InternalTexture(engine, dataSource) {
  20416. this.onLoadedObservable = new BABYLON.Observable();
  20417. // Private
  20418. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  20419. this._references = 1;
  20420. this._engine = engine;
  20421. this._dataSource = dataSource;
  20422. this._webGLTexture = engine._createTexture();
  20423. }
  20424. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  20425. get: function () {
  20426. return this._dataSource;
  20427. },
  20428. enumerable: true,
  20429. configurable: true
  20430. });
  20431. InternalTexture.prototype.incrementReferences = function () {
  20432. this._references++;
  20433. };
  20434. InternalTexture.prototype.updateSize = function (width, height) {
  20435. this.width = width;
  20436. this.height = height;
  20437. this._size = width * height;
  20438. this.baseWidth = width;
  20439. this.baseHeight = height;
  20440. };
  20441. InternalTexture.prototype._rebuild = function () {
  20442. var _this = this;
  20443. var proxy;
  20444. this.isReady = false;
  20445. this._cachedCoordinatesMode = null;
  20446. this._cachedWrapU = null;
  20447. this._cachedWrapV = null;
  20448. this._cachedAnisotropicFilteringLevel = null;
  20449. switch (this._dataSource) {
  20450. case InternalTexture.DATASOURCE_TEMP:
  20451. return;
  20452. case InternalTexture.DATASOURCE_URL:
  20453. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  20454. _this.isReady = true;
  20455. }, null, this._buffer, null, this.format);
  20456. proxy._swapAndDie(this);
  20457. return;
  20458. case InternalTexture.DATASOURCE_RAW:
  20459. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20460. proxy._swapAndDie(this);
  20461. this.isReady = true;
  20462. return;
  20463. case InternalTexture.DATASOURCE_DYNAMIC:
  20464. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  20465. proxy._swapAndDie(this);
  20466. // The engine will make sure to update content so no need to flag it as isReady = true
  20467. return;
  20468. case InternalTexture.DATASOURCE_RENDERTARGET:
  20469. var options = new BABYLON.RenderTargetCreationOptions();
  20470. options.generateDepthBuffer = this._generateDepthBuffer;
  20471. options.generateMipMaps = this.generateMipMaps;
  20472. options.generateStencilBuffer = this._generateStencilBuffer;
  20473. options.samplingMode = this.samplingMode;
  20474. options.type = this.type;
  20475. if (this.isCube) {
  20476. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20477. }
  20478. else {
  20479. var size = {
  20480. width: this.width,
  20481. height: this.height
  20482. };
  20483. proxy = this._engine.createRenderTargetTexture(size, options);
  20484. }
  20485. proxy._swapAndDie(this);
  20486. this.isReady = true;
  20487. return;
  20488. case InternalTexture.DATASOURCE_CUBE:
  20489. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20490. _this.isReady = true;
  20491. }, null, this.format, this._extension);
  20492. proxy._swapAndDie(this);
  20493. return;
  20494. case InternalTexture.DATASOURCE_CUBERAW:
  20495. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20496. proxy._swapAndDie(this);
  20497. this.isReady = true;
  20498. return;
  20499. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20500. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20501. proxy._swapAndDie(_this);
  20502. _this.isReady = true;
  20503. }, null, this.format, this._extension);
  20504. return;
  20505. }
  20506. };
  20507. InternalTexture.prototype._swapAndDie = function (target) {
  20508. target._webGLTexture = this._webGLTexture;
  20509. if (this._framebuffer) {
  20510. target._framebuffer = this._framebuffer;
  20511. }
  20512. if (this._depthStencilBuffer) {
  20513. target._depthStencilBuffer = this._depthStencilBuffer;
  20514. }
  20515. if (this._lodTextureHigh) {
  20516. if (target._lodTextureHigh) {
  20517. target._lodTextureHigh.dispose();
  20518. }
  20519. target._lodTextureHigh = this._lodTextureHigh;
  20520. }
  20521. if (this._lodTextureMid) {
  20522. if (target._lodTextureMid) {
  20523. target._lodTextureMid.dispose();
  20524. }
  20525. target._lodTextureMid = this._lodTextureMid;
  20526. }
  20527. if (this._lodTextureLow) {
  20528. if (target._lodTextureLow) {
  20529. target._lodTextureLow.dispose();
  20530. }
  20531. target._lodTextureLow = this._lodTextureLow;
  20532. }
  20533. var cache = this._engine.getLoadedTexturesCache();
  20534. var index = cache.indexOf(this);
  20535. if (index !== -1) {
  20536. cache.splice(index, 1);
  20537. }
  20538. };
  20539. InternalTexture.prototype.dispose = function () {
  20540. if (!this._webGLTexture) {
  20541. return;
  20542. }
  20543. this._references--;
  20544. if (this._references === 0) {
  20545. this._engine._releaseTexture(this);
  20546. this._webGLTexture = null;
  20547. }
  20548. };
  20549. return InternalTexture;
  20550. }());
  20551. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20552. InternalTexture.DATASOURCE_URL = 1;
  20553. InternalTexture.DATASOURCE_TEMP = 2;
  20554. InternalTexture.DATASOURCE_RAW = 3;
  20555. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20556. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20557. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20558. InternalTexture.DATASOURCE_CUBE = 7;
  20559. InternalTexture.DATASOURCE_CUBERAW = 8;
  20560. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20561. BABYLON.InternalTexture = InternalTexture;
  20562. })(BABYLON || (BABYLON = {}));
  20563. //# sourceMappingURL=babylon.internalTexture.js.map
  20564. var BABYLON;
  20565. (function (BABYLON) {
  20566. var BaseTexture = (function () {
  20567. function BaseTexture(scene) {
  20568. this._hasAlpha = false;
  20569. this.getAlphaFromRGB = false;
  20570. this.level = 1;
  20571. this.coordinatesIndex = 0;
  20572. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20573. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20574. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20575. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20576. this.isCube = false;
  20577. this.gammaSpace = true;
  20578. this.invertZ = false;
  20579. this.lodLevelInAlpha = false;
  20580. this.lodGenerationOffset = 0.0;
  20581. this.lodGenerationScale = 0.8;
  20582. this.isRenderTarget = false;
  20583. this.animations = new Array();
  20584. /**
  20585. * An event triggered when the texture is disposed.
  20586. * @type {BABYLON.Observable}
  20587. */
  20588. this.onDisposeObservable = new BABYLON.Observable();
  20589. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20590. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20591. this._scene.textures.push(this);
  20592. this._uid = null;
  20593. }
  20594. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20595. get: function () {
  20596. return this._hasAlpha;
  20597. },
  20598. set: function (value) {
  20599. if (this._hasAlpha === value) {
  20600. return;
  20601. }
  20602. this._hasAlpha = value;
  20603. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20604. },
  20605. enumerable: true,
  20606. configurable: true
  20607. });
  20608. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20609. get: function () {
  20610. return this._coordinatesMode;
  20611. },
  20612. set: function (value) {
  20613. if (this._coordinatesMode === value) {
  20614. return;
  20615. }
  20616. this._coordinatesMode = value;
  20617. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20618. },
  20619. enumerable: true,
  20620. configurable: true
  20621. });
  20622. Object.defineProperty(BaseTexture.prototype, "uid", {
  20623. get: function () {
  20624. if (!this._uid) {
  20625. this._uid = BABYLON.Tools.RandomId();
  20626. }
  20627. return this._uid;
  20628. },
  20629. enumerable: true,
  20630. configurable: true
  20631. });
  20632. BaseTexture.prototype.toString = function () {
  20633. return this.name;
  20634. };
  20635. BaseTexture.prototype.getClassName = function () {
  20636. return "BaseTexture";
  20637. };
  20638. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20639. set: function (callback) {
  20640. if (this._onDisposeObserver) {
  20641. this.onDisposeObservable.remove(this._onDisposeObserver);
  20642. }
  20643. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20644. },
  20645. enumerable: true,
  20646. configurable: true
  20647. });
  20648. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20649. get: function () {
  20650. return true;
  20651. },
  20652. enumerable: true,
  20653. configurable: true
  20654. });
  20655. BaseTexture.prototype.getScene = function () {
  20656. return this._scene;
  20657. };
  20658. BaseTexture.prototype.getTextureMatrix = function () {
  20659. return null;
  20660. };
  20661. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20662. return null;
  20663. };
  20664. BaseTexture.prototype.getInternalTexture = function () {
  20665. return this._texture;
  20666. };
  20667. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20668. return !this.isBlocking || this.isReady();
  20669. };
  20670. BaseTexture.prototype.isReady = function () {
  20671. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20672. this.delayLoad();
  20673. return false;
  20674. }
  20675. if (this._texture) {
  20676. return this._texture.isReady;
  20677. }
  20678. return false;
  20679. };
  20680. BaseTexture.prototype.getSize = function () {
  20681. if (this._texture.width) {
  20682. return new BABYLON.Size(this._texture.width, this._texture.height);
  20683. }
  20684. if (this._texture._size) {
  20685. return new BABYLON.Size(this._texture._size, this._texture._size);
  20686. }
  20687. return BABYLON.Size.Zero();
  20688. };
  20689. BaseTexture.prototype.getBaseSize = function () {
  20690. if (!this.isReady() || !this._texture)
  20691. return BABYLON.Size.Zero();
  20692. if (this._texture._size) {
  20693. return new BABYLON.Size(this._texture._size, this._texture._size);
  20694. }
  20695. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20696. };
  20697. BaseTexture.prototype.scale = function (ratio) {
  20698. };
  20699. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20700. get: function () {
  20701. return false;
  20702. },
  20703. enumerable: true,
  20704. configurable: true
  20705. });
  20706. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20707. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20708. for (var index = 0; index < texturesCache.length; index++) {
  20709. var texturesCacheEntry = texturesCache[index];
  20710. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20711. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20712. texturesCacheEntry.incrementReferences();
  20713. return texturesCacheEntry;
  20714. }
  20715. }
  20716. }
  20717. return null;
  20718. };
  20719. BaseTexture.prototype._rebuild = function () {
  20720. };
  20721. BaseTexture.prototype.delayLoad = function () {
  20722. };
  20723. BaseTexture.prototype.clone = function () {
  20724. return null;
  20725. };
  20726. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20727. get: function () {
  20728. if (!this._texture) {
  20729. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20730. }
  20731. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20732. },
  20733. enumerable: true,
  20734. configurable: true
  20735. });
  20736. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20737. get: function () {
  20738. if (!this._texture) {
  20739. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20740. }
  20741. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20742. },
  20743. enumerable: true,
  20744. configurable: true
  20745. });
  20746. BaseTexture.prototype.readPixels = function (faceIndex) {
  20747. if (faceIndex === void 0) { faceIndex = 0; }
  20748. if (!this._texture) {
  20749. return null;
  20750. }
  20751. var size = this.getSize();
  20752. var engine = this.getScene().getEngine();
  20753. if (this._texture.isCube) {
  20754. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20755. }
  20756. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20757. };
  20758. BaseTexture.prototype.releaseInternalTexture = function () {
  20759. if (this._texture) {
  20760. this._texture.dispose();
  20761. this._texture = null;
  20762. }
  20763. };
  20764. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20765. get: function () {
  20766. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20767. return null;
  20768. }
  20769. if (!this._texture._sphericalPolynomial) {
  20770. this._texture._sphericalPolynomial =
  20771. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20772. }
  20773. return this._texture._sphericalPolynomial;
  20774. },
  20775. set: function (value) {
  20776. if (this._texture) {
  20777. this._texture._sphericalPolynomial = value;
  20778. }
  20779. },
  20780. enumerable: true,
  20781. configurable: true
  20782. });
  20783. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20784. get: function () {
  20785. if (this._texture) {
  20786. return this._texture._lodTextureHigh;
  20787. }
  20788. return null;
  20789. },
  20790. enumerable: true,
  20791. configurable: true
  20792. });
  20793. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20794. get: function () {
  20795. if (this._texture) {
  20796. return this._texture._lodTextureMid;
  20797. }
  20798. return null;
  20799. },
  20800. enumerable: true,
  20801. configurable: true
  20802. });
  20803. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20804. get: function () {
  20805. if (this._texture) {
  20806. return this._texture._lodTextureLow;
  20807. }
  20808. return null;
  20809. },
  20810. enumerable: true,
  20811. configurable: true
  20812. });
  20813. BaseTexture.prototype.dispose = function () {
  20814. // Animations
  20815. this.getScene().stopAnimation(this);
  20816. // Remove from scene
  20817. this._scene._removePendingData(this);
  20818. var index = this._scene.textures.indexOf(this);
  20819. if (index >= 0) {
  20820. this._scene.textures.splice(index, 1);
  20821. }
  20822. if (this._texture === undefined) {
  20823. return;
  20824. }
  20825. // Release
  20826. this.releaseInternalTexture();
  20827. // Callback
  20828. this.onDisposeObservable.notifyObservers(this);
  20829. this.onDisposeObservable.clear();
  20830. };
  20831. BaseTexture.prototype.serialize = function () {
  20832. if (!this.name) {
  20833. return null;
  20834. }
  20835. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20836. // Animations
  20837. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20838. return serializationObject;
  20839. };
  20840. BaseTexture.WhenAllReady = function (textures, callback) {
  20841. var numRemaining = textures.length;
  20842. if (numRemaining === 0) {
  20843. callback();
  20844. return;
  20845. }
  20846. var _loop_1 = function () {
  20847. texture = textures[i];
  20848. if (texture.isReady()) {
  20849. if (--numRemaining === 0) {
  20850. callback();
  20851. }
  20852. }
  20853. else {
  20854. onLoadObservable = texture.onLoadObservable;
  20855. var onLoadCallback_1 = function () {
  20856. onLoadObservable.removeCallback(onLoadCallback_1);
  20857. if (--numRemaining === 0) {
  20858. callback();
  20859. }
  20860. };
  20861. onLoadObservable.add(onLoadCallback_1);
  20862. }
  20863. };
  20864. var texture, onLoadObservable;
  20865. for (var i = 0; i < textures.length; i++) {
  20866. _loop_1();
  20867. }
  20868. };
  20869. return BaseTexture;
  20870. }());
  20871. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20872. __decorate([
  20873. BABYLON.serialize()
  20874. ], BaseTexture.prototype, "name", void 0);
  20875. __decorate([
  20876. BABYLON.serialize("hasAlpha")
  20877. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20878. __decorate([
  20879. BABYLON.serialize()
  20880. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20881. __decorate([
  20882. BABYLON.serialize()
  20883. ], BaseTexture.prototype, "level", void 0);
  20884. __decorate([
  20885. BABYLON.serialize()
  20886. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20887. __decorate([
  20888. BABYLON.serialize("coordinatesMode")
  20889. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20890. __decorate([
  20891. BABYLON.serialize()
  20892. ], BaseTexture.prototype, "wrapU", void 0);
  20893. __decorate([
  20894. BABYLON.serialize()
  20895. ], BaseTexture.prototype, "wrapV", void 0);
  20896. __decorate([
  20897. BABYLON.serialize()
  20898. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20899. __decorate([
  20900. BABYLON.serialize()
  20901. ], BaseTexture.prototype, "isCube", void 0);
  20902. __decorate([
  20903. BABYLON.serialize()
  20904. ], BaseTexture.prototype, "gammaSpace", void 0);
  20905. __decorate([
  20906. BABYLON.serialize()
  20907. ], BaseTexture.prototype, "invertZ", void 0);
  20908. __decorate([
  20909. BABYLON.serialize()
  20910. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20911. __decorate([
  20912. BABYLON.serialize()
  20913. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20914. __decorate([
  20915. BABYLON.serialize()
  20916. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20917. __decorate([
  20918. BABYLON.serialize()
  20919. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20920. BABYLON.BaseTexture = BaseTexture;
  20921. })(BABYLON || (BABYLON = {}));
  20922. //# sourceMappingURL=babylon.baseTexture.js.map
  20923. var BABYLON;
  20924. (function (BABYLON) {
  20925. var Texture = (function (_super) {
  20926. __extends(Texture, _super);
  20927. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20928. if (noMipmap === void 0) { noMipmap = false; }
  20929. if (invertY === void 0) { invertY = true; }
  20930. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20931. if (onLoad === void 0) { onLoad = null; }
  20932. if (onError === void 0) { onError = null; }
  20933. if (buffer === void 0) { buffer = null; }
  20934. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20935. var _this = _super.call(this, scene) || this;
  20936. _this.uOffset = 0;
  20937. _this.vOffset = 0;
  20938. _this.uScale = 1.0;
  20939. _this.vScale = 1.0;
  20940. _this.uAng = 0;
  20941. _this.vAng = 0;
  20942. _this.wAng = 0;
  20943. _this._isBlocking = true;
  20944. _this.name = url;
  20945. _this.url = url;
  20946. _this._noMipmap = noMipmap;
  20947. _this._invertY = invertY;
  20948. _this._samplingMode = samplingMode;
  20949. _this._buffer = buffer;
  20950. _this._deleteBuffer = deleteBuffer;
  20951. _this._format = format;
  20952. scene = _this.getScene();
  20953. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  20954. var load = function () {
  20955. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20956. _this.onLoadObservable.notifyObservers(_this);
  20957. }
  20958. if (onLoad) {
  20959. onLoad();
  20960. }
  20961. if (!_this.isBlocking) {
  20962. scene.resetCachedMaterial();
  20963. }
  20964. };
  20965. if (!_this.url) {
  20966. _this._delayedOnLoad = load;
  20967. _this._delayedOnError = onError;
  20968. return _this;
  20969. }
  20970. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  20971. if (!_this._texture) {
  20972. if (!scene.useDelayedTextureLoading) {
  20973. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20974. if (deleteBuffer) {
  20975. delete _this._buffer;
  20976. }
  20977. }
  20978. else {
  20979. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20980. _this._delayedOnLoad = load;
  20981. _this._delayedOnError = onError;
  20982. }
  20983. }
  20984. else {
  20985. if (_this._texture.isReady) {
  20986. BABYLON.Tools.SetImmediate(function () { return load(); });
  20987. }
  20988. else {
  20989. _this._texture.onLoadedObservable.add(load);
  20990. }
  20991. }
  20992. return _this;
  20993. }
  20994. Object.defineProperty(Texture.prototype, "noMipmap", {
  20995. get: function () {
  20996. return this._noMipmap;
  20997. },
  20998. enumerable: true,
  20999. configurable: true
  21000. });
  21001. Object.defineProperty(Texture.prototype, "isBlocking", {
  21002. get: function () {
  21003. return this._isBlocking;
  21004. },
  21005. set: function (value) {
  21006. this._isBlocking = value;
  21007. },
  21008. enumerable: true,
  21009. configurable: true
  21010. });
  21011. Object.defineProperty(Texture.prototype, "samplingMode", {
  21012. get: function () {
  21013. return this._samplingMode;
  21014. },
  21015. enumerable: true,
  21016. configurable: true
  21017. });
  21018. Texture.prototype.updateURL = function (url) {
  21019. this.url = url;
  21020. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21021. this.delayLoad();
  21022. };
  21023. Texture.prototype.delayLoad = function () {
  21024. var _this = this;
  21025. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21026. return;
  21027. }
  21028. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21029. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21030. if (!this._texture) {
  21031. 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);
  21032. if (this._deleteBuffer) {
  21033. delete this._buffer;
  21034. }
  21035. }
  21036. else {
  21037. if (this._texture.isReady) {
  21038. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  21039. }
  21040. else {
  21041. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  21042. }
  21043. }
  21044. };
  21045. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21046. if (!this._texture) {
  21047. return;
  21048. }
  21049. this._samplingMode = samplingMode;
  21050. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21051. };
  21052. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21053. x *= this.uScale;
  21054. y *= this.vScale;
  21055. x -= 0.5 * this.uScale;
  21056. y -= 0.5 * this.vScale;
  21057. z -= 0.5;
  21058. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21059. t.x += 0.5 * this.uScale + this.uOffset;
  21060. t.y += 0.5 * this.vScale + this.vOffset;
  21061. t.z += 0.5;
  21062. };
  21063. Texture.prototype.getTextureMatrix = function () {
  21064. var _this = this;
  21065. if (this.uOffset === this._cachedUOffset &&
  21066. this.vOffset === this._cachedVOffset &&
  21067. this.uScale === this._cachedUScale &&
  21068. this.vScale === this._cachedVScale &&
  21069. this.uAng === this._cachedUAng &&
  21070. this.vAng === this._cachedVAng &&
  21071. this.wAng === this._cachedWAng) {
  21072. return this._cachedTextureMatrix;
  21073. }
  21074. this._cachedUOffset = this.uOffset;
  21075. this._cachedVOffset = this.vOffset;
  21076. this._cachedUScale = this.uScale;
  21077. this._cachedVScale = this.vScale;
  21078. this._cachedUAng = this.uAng;
  21079. this._cachedVAng = this.vAng;
  21080. this._cachedWAng = this.wAng;
  21081. if (!this._cachedTextureMatrix) {
  21082. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21083. this._rowGenerationMatrix = new BABYLON.Matrix();
  21084. this._t0 = BABYLON.Vector3.Zero();
  21085. this._t1 = BABYLON.Vector3.Zero();
  21086. this._t2 = BABYLON.Vector3.Zero();
  21087. }
  21088. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21089. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21090. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21091. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21092. this._t1.subtractInPlace(this._t0);
  21093. this._t2.subtractInPlace(this._t0);
  21094. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21095. this._cachedTextureMatrix.m[0] = this._t1.x;
  21096. this._cachedTextureMatrix.m[1] = this._t1.y;
  21097. this._cachedTextureMatrix.m[2] = this._t1.z;
  21098. this._cachedTextureMatrix.m[4] = this._t2.x;
  21099. this._cachedTextureMatrix.m[5] = this._t2.y;
  21100. this._cachedTextureMatrix.m[6] = this._t2.z;
  21101. this._cachedTextureMatrix.m[8] = this._t0.x;
  21102. this._cachedTextureMatrix.m[9] = this._t0.y;
  21103. this._cachedTextureMatrix.m[10] = this._t0.z;
  21104. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21105. return mat.hasTexture(_this);
  21106. });
  21107. return this._cachedTextureMatrix;
  21108. };
  21109. Texture.prototype.getReflectionTextureMatrix = function () {
  21110. var _this = this;
  21111. var scene = this.getScene();
  21112. if (this.uOffset === this._cachedUOffset &&
  21113. this.vOffset === this._cachedVOffset &&
  21114. this.uScale === this._cachedUScale &&
  21115. this.vScale === this._cachedVScale &&
  21116. this.coordinatesMode === this._cachedCoordinatesMode) {
  21117. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  21118. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  21119. return this._cachedTextureMatrix;
  21120. }
  21121. }
  21122. else {
  21123. return this._cachedTextureMatrix;
  21124. }
  21125. }
  21126. if (!this._cachedTextureMatrix) {
  21127. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21128. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21129. }
  21130. this._cachedUOffset = this.uOffset;
  21131. this._cachedVOffset = this.vOffset;
  21132. this._cachedUScale = this.uScale;
  21133. this._cachedVScale = this.vScale;
  21134. this._cachedCoordinatesMode = this.coordinatesMode;
  21135. switch (this.coordinatesMode) {
  21136. case Texture.PLANAR_MODE:
  21137. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21138. this._cachedTextureMatrix[0] = this.uScale;
  21139. this._cachedTextureMatrix[5] = this.vScale;
  21140. this._cachedTextureMatrix[12] = this.uOffset;
  21141. this._cachedTextureMatrix[13] = this.vOffset;
  21142. break;
  21143. case Texture.PROJECTION_MODE:
  21144. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21145. this._projectionModeMatrix.m[0] = 0.5;
  21146. this._projectionModeMatrix.m[5] = -0.5;
  21147. this._projectionModeMatrix.m[10] = 0.0;
  21148. this._projectionModeMatrix.m[12] = 0.5;
  21149. this._projectionModeMatrix.m[13] = 0.5;
  21150. this._projectionModeMatrix.m[14] = 1.0;
  21151. this._projectionModeMatrix.m[15] = 1.0;
  21152. var projectionMatrix = scene.getProjectionMatrix();
  21153. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  21154. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21155. break;
  21156. default:
  21157. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21158. break;
  21159. }
  21160. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21161. return (mat.getActiveTextures().indexOf(_this) !== -1);
  21162. });
  21163. return this._cachedTextureMatrix;
  21164. };
  21165. Texture.prototype.clone = function () {
  21166. var _this = this;
  21167. return BABYLON.SerializationHelper.Clone(function () {
  21168. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21169. }, this);
  21170. };
  21171. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  21172. get: function () {
  21173. if (!this._onLoadObservable) {
  21174. this._onLoadObservable = new BABYLON.Observable();
  21175. }
  21176. return this._onLoadObservable;
  21177. },
  21178. enumerable: true,
  21179. configurable: true
  21180. });
  21181. Texture.prototype.serialize = function () {
  21182. var serializationObject = _super.prototype.serialize.call(this);
  21183. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  21184. serializationObject.base64String = this._buffer;
  21185. serializationObject.name = serializationObject.name.replace("data:", "");
  21186. }
  21187. return serializationObject;
  21188. };
  21189. Texture.prototype.getClassName = function () {
  21190. return "Texture";
  21191. };
  21192. Texture.prototype.dispose = function () {
  21193. _super.prototype.dispose.call(this);
  21194. if (this.onLoadObservable) {
  21195. this.onLoadObservable.clear();
  21196. this._onLoadObservable = null;
  21197. }
  21198. this._delayedOnLoad = null;
  21199. this._delayedOnError = null;
  21200. };
  21201. // Statics
  21202. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21203. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21204. if (onLoad === void 0) { onLoad = null; }
  21205. if (onError === void 0) { onError = null; }
  21206. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21207. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  21208. };
  21209. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21210. if (parsedTexture.customType) {
  21211. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  21212. // Update Sampling Mode
  21213. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  21214. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  21215. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  21216. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  21217. }
  21218. }
  21219. return parsedCustomTexture;
  21220. }
  21221. if (parsedTexture.isCube) {
  21222. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21223. }
  21224. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21225. return null;
  21226. }
  21227. var texture = BABYLON.SerializationHelper.Parse(function () {
  21228. if (parsedTexture.mirrorPlane) {
  21229. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21230. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21231. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21232. return mirrorTexture;
  21233. }
  21234. else if (parsedTexture.isRenderTarget) {
  21235. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21236. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21237. return renderTargetTexture;
  21238. }
  21239. else {
  21240. var texture;
  21241. if (parsedTexture.base64String) {
  21242. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21243. }
  21244. else {
  21245. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21246. }
  21247. return texture;
  21248. }
  21249. }, parsedTexture, scene);
  21250. // Update Sampling Mode
  21251. if (parsedTexture.samplingMode) {
  21252. var sampling = parsedTexture.samplingMode;
  21253. if (texture._samplingMode !== sampling) {
  21254. texture.updateSamplingMode(sampling);
  21255. }
  21256. }
  21257. // Animations
  21258. if (parsedTexture.animations) {
  21259. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21260. var parsedAnimation = parsedTexture.animations[animationIndex];
  21261. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21262. }
  21263. }
  21264. return texture;
  21265. };
  21266. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21267. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21268. if (noMipmap === void 0) { noMipmap = false; }
  21269. if (invertY === void 0) { invertY = true; }
  21270. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21271. if (onLoad === void 0) { onLoad = null; }
  21272. if (onError === void 0) { onError = null; }
  21273. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21274. if (name.substr(0, 5) !== "data:") {
  21275. name = "data:" + name;
  21276. }
  21277. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  21278. };
  21279. return Texture;
  21280. }(BABYLON.BaseTexture));
  21281. // Constants
  21282. Texture.NEAREST_SAMPLINGMODE = 1;
  21283. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  21284. Texture.BILINEAR_SAMPLINGMODE = 2;
  21285. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  21286. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21287. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  21288. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  21289. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  21290. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  21291. Texture.NEAREST_LINEAR = 7;
  21292. Texture.NEAREST_NEAREST = 8;
  21293. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  21294. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  21295. Texture.LINEAR_LINEAR = 11;
  21296. Texture.LINEAR_NEAREST = 12;
  21297. Texture.EXPLICIT_MODE = 0;
  21298. Texture.SPHERICAL_MODE = 1;
  21299. Texture.PLANAR_MODE = 2;
  21300. Texture.CUBIC_MODE = 3;
  21301. Texture.PROJECTION_MODE = 4;
  21302. Texture.SKYBOX_MODE = 5;
  21303. Texture.INVCUBIC_MODE = 6;
  21304. Texture.EQUIRECTANGULAR_MODE = 7;
  21305. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21306. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  21307. Texture.CLAMP_ADDRESSMODE = 0;
  21308. Texture.WRAP_ADDRESSMODE = 1;
  21309. Texture.MIRROR_ADDRESSMODE = 2;
  21310. __decorate([
  21311. BABYLON.serialize()
  21312. ], Texture.prototype, "url", void 0);
  21313. __decorate([
  21314. BABYLON.serialize()
  21315. ], Texture.prototype, "uOffset", void 0);
  21316. __decorate([
  21317. BABYLON.serialize()
  21318. ], Texture.prototype, "vOffset", void 0);
  21319. __decorate([
  21320. BABYLON.serialize()
  21321. ], Texture.prototype, "uScale", void 0);
  21322. __decorate([
  21323. BABYLON.serialize()
  21324. ], Texture.prototype, "vScale", void 0);
  21325. __decorate([
  21326. BABYLON.serialize()
  21327. ], Texture.prototype, "uAng", void 0);
  21328. __decorate([
  21329. BABYLON.serialize()
  21330. ], Texture.prototype, "vAng", void 0);
  21331. __decorate([
  21332. BABYLON.serialize()
  21333. ], Texture.prototype, "wAng", void 0);
  21334. __decorate([
  21335. BABYLON.serialize()
  21336. ], Texture.prototype, "isBlocking", null);
  21337. BABYLON.Texture = Texture;
  21338. })(BABYLON || (BABYLON = {}));
  21339. //# sourceMappingURL=babylon.texture.js.map
  21340. var BABYLON;
  21341. (function (BABYLON) {
  21342. var _InstancesBatch = (function () {
  21343. function _InstancesBatch() {
  21344. this.mustReturn = false;
  21345. this.visibleInstances = new Array();
  21346. this.renderSelf = new Array();
  21347. }
  21348. return _InstancesBatch;
  21349. }());
  21350. BABYLON._InstancesBatch = _InstancesBatch;
  21351. var Mesh = (function (_super) {
  21352. __extends(Mesh, _super);
  21353. /**
  21354. * @constructor
  21355. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  21356. * @param {Scene} scene The scene to add this mesh to.
  21357. * @param {Node} parent The parent of this mesh, if it has one
  21358. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  21359. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  21360. * When false, achieved by calling a clone(), also passing False.
  21361. * This will make creation of children, recursive.
  21362. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  21363. */
  21364. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  21365. if (parent === void 0) { parent = null; }
  21366. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21367. var _this = _super.call(this, name, scene) || this;
  21368. // Events
  21369. /**
  21370. * An event triggered before rendering the mesh
  21371. * @type {BABYLON.Observable}
  21372. */
  21373. _this.onBeforeRenderObservable = new BABYLON.Observable();
  21374. /**
  21375. * An event triggered after rendering the mesh
  21376. * @type {BABYLON.Observable}
  21377. */
  21378. _this.onAfterRenderObservable = new BABYLON.Observable();
  21379. /**
  21380. * An event triggered before drawing the mesh
  21381. * @type {BABYLON.Observable}
  21382. */
  21383. _this.onBeforeDrawObservable = new BABYLON.Observable();
  21384. // Members
  21385. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21386. _this.instances = new Array();
  21387. _this._LODLevels = new Array();
  21388. _this._visibleInstances = {};
  21389. _this._renderIdForInstances = new Array();
  21390. _this._batchCache = new _InstancesBatch();
  21391. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  21392. // Use by builder only to know what orientation were the mesh build in.
  21393. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  21394. _this.overrideMaterialSideOrientation = null;
  21395. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  21396. // Will be used to save a source mesh reference, If any
  21397. _this._source = null;
  21398. if (source) {
  21399. // Source mesh
  21400. _this._source = source;
  21401. // Geometry
  21402. if (source._geometry) {
  21403. source._geometry.applyToMesh(_this);
  21404. }
  21405. // Deep copy
  21406. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  21407. // Parent
  21408. _this.parent = source.parent;
  21409. // Pivot
  21410. _this.setPivotMatrix(source.getPivotMatrix());
  21411. _this.id = name + "." + source.id;
  21412. // Material
  21413. _this.material = source.material;
  21414. var index;
  21415. if (!doNotCloneChildren) {
  21416. // Children
  21417. for (index = 0; index < scene.meshes.length; index++) {
  21418. var mesh = scene.meshes[index];
  21419. if (mesh.parent === source) {
  21420. // doNotCloneChildren is always going to be False
  21421. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  21422. }
  21423. }
  21424. }
  21425. // Physics clone
  21426. var physicsEngine = _this.getScene().getPhysicsEngine();
  21427. if (clonePhysicsImpostor && physicsEngine) {
  21428. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  21429. if (impostor) {
  21430. _this.physicsImpostor = impostor.clone(_this);
  21431. }
  21432. }
  21433. // Particles
  21434. for (index = 0; index < scene.particleSystems.length; index++) {
  21435. var system = scene.particleSystems[index];
  21436. if (system.emitter === source) {
  21437. system.clone(system.name, _this);
  21438. }
  21439. }
  21440. _this.computeWorldMatrix(true);
  21441. }
  21442. // Parent
  21443. if (parent !== null) {
  21444. _this.parent = parent;
  21445. }
  21446. return _this;
  21447. }
  21448. Object.defineProperty(Mesh, "FRONTSIDE", {
  21449. /**
  21450. * Mesh side orientation : usually the external or front surface
  21451. */
  21452. get: function () {
  21453. return Mesh._FRONTSIDE;
  21454. },
  21455. enumerable: true,
  21456. configurable: true
  21457. });
  21458. Object.defineProperty(Mesh, "BACKSIDE", {
  21459. /**
  21460. * Mesh side orientation : usually the internal or back surface
  21461. */
  21462. get: function () {
  21463. return Mesh._BACKSIDE;
  21464. },
  21465. enumerable: true,
  21466. configurable: true
  21467. });
  21468. Object.defineProperty(Mesh, "DOUBLESIDE", {
  21469. /**
  21470. * Mesh side orientation : both internal and external or front and back surfaces
  21471. */
  21472. get: function () {
  21473. return Mesh._DOUBLESIDE;
  21474. },
  21475. enumerable: true,
  21476. configurable: true
  21477. });
  21478. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21479. /**
  21480. * Mesh side orientation : by default, `FRONTSIDE`
  21481. */
  21482. get: function () {
  21483. return Mesh._DEFAULTSIDE;
  21484. },
  21485. enumerable: true,
  21486. configurable: true
  21487. });
  21488. Object.defineProperty(Mesh, "NO_CAP", {
  21489. /**
  21490. * Mesh cap setting : no cap
  21491. */
  21492. get: function () {
  21493. return Mesh._NO_CAP;
  21494. },
  21495. enumerable: true,
  21496. configurable: true
  21497. });
  21498. Object.defineProperty(Mesh, "CAP_START", {
  21499. /**
  21500. * Mesh cap setting : one cap at the beginning of the mesh
  21501. */
  21502. get: function () {
  21503. return Mesh._CAP_START;
  21504. },
  21505. enumerable: true,
  21506. configurable: true
  21507. });
  21508. Object.defineProperty(Mesh, "CAP_END", {
  21509. /**
  21510. * Mesh cap setting : one cap at the end of the mesh
  21511. */
  21512. get: function () {
  21513. return Mesh._CAP_END;
  21514. },
  21515. enumerable: true,
  21516. configurable: true
  21517. });
  21518. Object.defineProperty(Mesh, "CAP_ALL", {
  21519. /**
  21520. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21521. */
  21522. get: function () {
  21523. return Mesh._CAP_ALL;
  21524. },
  21525. enumerable: true,
  21526. configurable: true
  21527. });
  21528. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21529. set: function (callback) {
  21530. if (this._onBeforeDrawObserver) {
  21531. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21532. }
  21533. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21534. },
  21535. enumerable: true,
  21536. configurable: true
  21537. });
  21538. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21539. get: function () {
  21540. return this._morphTargetManager;
  21541. },
  21542. set: function (value) {
  21543. if (this._morphTargetManager === value) {
  21544. return;
  21545. }
  21546. this._morphTargetManager = value;
  21547. this._syncGeometryWithMorphTargetManager();
  21548. },
  21549. enumerable: true,
  21550. configurable: true
  21551. });
  21552. Object.defineProperty(Mesh.prototype, "source", {
  21553. get: function () {
  21554. return this._source;
  21555. },
  21556. enumerable: true,
  21557. configurable: true
  21558. });
  21559. // Methods
  21560. /**
  21561. * Returns the string "Mesh".
  21562. */
  21563. Mesh.prototype.getClassName = function () {
  21564. return "Mesh";
  21565. };
  21566. /**
  21567. * Returns a string.
  21568. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21569. */
  21570. Mesh.prototype.toString = function (fullDetails) {
  21571. var ret = _super.prototype.toString.call(this, fullDetails);
  21572. ret += ", n vertices: " + this.getTotalVertices();
  21573. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21574. if (this.animations) {
  21575. for (var i = 0; i < this.animations.length; i++) {
  21576. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21577. }
  21578. }
  21579. if (fullDetails) {
  21580. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21581. }
  21582. return ret;
  21583. };
  21584. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21585. /**
  21586. * True if the mesh has some Levels Of Details (LOD).
  21587. * Returns a boolean.
  21588. */
  21589. get: function () {
  21590. return this._LODLevels.length > 0;
  21591. },
  21592. enumerable: true,
  21593. configurable: true
  21594. });
  21595. Mesh.prototype._sortLODLevels = function () {
  21596. this._LODLevels.sort(function (a, b) {
  21597. if (a.distance < b.distance) {
  21598. return 1;
  21599. }
  21600. if (a.distance > b.distance) {
  21601. return -1;
  21602. }
  21603. return 0;
  21604. });
  21605. };
  21606. /**
  21607. * Add a mesh as LOD level triggered at the given distance.
  21608. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21609. * @param {number} distance The distance from the center of the object to show this level
  21610. * @param {Mesh} mesh The mesh to be added as LOD level
  21611. * @return {Mesh} This mesh (for chaining)
  21612. */
  21613. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21614. if (mesh && mesh._masterMesh) {
  21615. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21616. return this;
  21617. }
  21618. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21619. this._LODLevels.push(level);
  21620. if (mesh) {
  21621. mesh._masterMesh = this;
  21622. }
  21623. this._sortLODLevels();
  21624. return this;
  21625. };
  21626. /**
  21627. * Returns the LOD level mesh at the passed distance or null if not found.
  21628. * It is related to the method `addLODLevel(distance, mesh)`.
  21629. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21630. * Returns an object Mesh or `null`.
  21631. */
  21632. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21633. for (var index = 0; index < this._LODLevels.length; index++) {
  21634. var level = this._LODLevels[index];
  21635. if (level.distance === distance) {
  21636. return level.mesh;
  21637. }
  21638. }
  21639. return null;
  21640. };
  21641. /**
  21642. * Remove a mesh from the LOD array
  21643. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21644. * @param {Mesh} mesh The mesh to be removed.
  21645. * @return {Mesh} This mesh (for chaining)
  21646. */
  21647. Mesh.prototype.removeLODLevel = function (mesh) {
  21648. for (var index = 0; index < this._LODLevels.length; index++) {
  21649. if (this._LODLevels[index].mesh === mesh) {
  21650. this._LODLevels.splice(index, 1);
  21651. if (mesh) {
  21652. mesh._masterMesh = null;
  21653. }
  21654. }
  21655. }
  21656. this._sortLODLevels();
  21657. return this;
  21658. };
  21659. /**
  21660. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21661. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21662. */
  21663. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21664. if (!this._LODLevels || this._LODLevels.length === 0) {
  21665. return this;
  21666. }
  21667. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21668. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21669. if (this.onLODLevelSelection) {
  21670. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21671. }
  21672. return this;
  21673. }
  21674. for (var index = 0; index < this._LODLevels.length; index++) {
  21675. var level = this._LODLevels[index];
  21676. if (level.distance < distanceToCamera) {
  21677. if (level.mesh) {
  21678. level.mesh._preActivate();
  21679. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21680. }
  21681. if (this.onLODLevelSelection) {
  21682. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21683. }
  21684. return level.mesh;
  21685. }
  21686. }
  21687. if (this.onLODLevelSelection) {
  21688. this.onLODLevelSelection(distanceToCamera, this, this);
  21689. }
  21690. return this;
  21691. };
  21692. Object.defineProperty(Mesh.prototype, "geometry", {
  21693. /**
  21694. * Returns the mesh internal Geometry object.
  21695. */
  21696. get: function () {
  21697. return this._geometry;
  21698. },
  21699. enumerable: true,
  21700. configurable: true
  21701. });
  21702. /**
  21703. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21704. */
  21705. Mesh.prototype.getTotalVertices = function () {
  21706. if (!this._geometry) {
  21707. return 0;
  21708. }
  21709. return this._geometry.getTotalVertices();
  21710. };
  21711. /**
  21712. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21713. * 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.
  21714. * You can force the copy with forceCopy === true
  21715. * Returns null if the mesh has no geometry or no vertex buffer.
  21716. * Possible `kind` values :
  21717. * - BABYLON.VertexBuffer.PositionKind
  21718. * - BABYLON.VertexBuffer.UVKind
  21719. * - BABYLON.VertexBuffer.UV2Kind
  21720. * - BABYLON.VertexBuffer.UV3Kind
  21721. * - BABYLON.VertexBuffer.UV4Kind
  21722. * - BABYLON.VertexBuffer.UV5Kind
  21723. * - BABYLON.VertexBuffer.UV6Kind
  21724. * - BABYLON.VertexBuffer.ColorKind
  21725. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21726. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21727. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21728. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21729. */
  21730. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21731. if (!this._geometry) {
  21732. return null;
  21733. }
  21734. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21735. };
  21736. /**
  21737. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21738. * Returns `undefined` if the mesh has no geometry.
  21739. * Possible `kind` values :
  21740. * - BABYLON.VertexBuffer.PositionKind
  21741. * - BABYLON.VertexBuffer.UVKind
  21742. * - BABYLON.VertexBuffer.UV2Kind
  21743. * - BABYLON.VertexBuffer.UV3Kind
  21744. * - BABYLON.VertexBuffer.UV4Kind
  21745. * - BABYLON.VertexBuffer.UV5Kind
  21746. * - BABYLON.VertexBuffer.UV6Kind
  21747. * - BABYLON.VertexBuffer.ColorKind
  21748. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21749. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21750. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21751. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21752. */
  21753. Mesh.prototype.getVertexBuffer = function (kind) {
  21754. if (!this._geometry) {
  21755. return undefined;
  21756. }
  21757. return this._geometry.getVertexBuffer(kind);
  21758. };
  21759. /**
  21760. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21761. * Possible `kind` values :
  21762. * - BABYLON.VertexBuffer.PositionKind
  21763. * - BABYLON.VertexBuffer.UVKind
  21764. * - BABYLON.VertexBuffer.UV2Kind
  21765. * - BABYLON.VertexBuffer.UV3Kind
  21766. * - BABYLON.VertexBuffer.UV4Kind
  21767. * - BABYLON.VertexBuffer.UV5Kind
  21768. * - BABYLON.VertexBuffer.UV6Kind
  21769. * - BABYLON.VertexBuffer.ColorKind
  21770. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21771. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21772. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21773. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21774. */
  21775. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21776. if (!this._geometry) {
  21777. if (this._delayInfo) {
  21778. return this._delayInfo.indexOf(kind) !== -1;
  21779. }
  21780. return false;
  21781. }
  21782. return this._geometry.isVerticesDataPresent(kind);
  21783. };
  21784. /**
  21785. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21786. * Possible `kind` values :
  21787. * - BABYLON.VertexBuffer.PositionKind
  21788. * - BABYLON.VertexBuffer.UVKind
  21789. * - BABYLON.VertexBuffer.UV2Kind
  21790. * - BABYLON.VertexBuffer.UV3Kind
  21791. * - BABYLON.VertexBuffer.UV4Kind
  21792. * - BABYLON.VertexBuffer.UV5Kind
  21793. * - BABYLON.VertexBuffer.UV6Kind
  21794. * - BABYLON.VertexBuffer.ColorKind
  21795. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21796. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21797. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21798. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21799. */
  21800. Mesh.prototype.getVerticesDataKinds = function () {
  21801. if (!this._geometry) {
  21802. var result = [];
  21803. if (this._delayInfo) {
  21804. this._delayInfo.forEach(function (kind, index, array) {
  21805. result.push(kind);
  21806. });
  21807. }
  21808. return result;
  21809. }
  21810. return this._geometry.getVerticesDataKinds();
  21811. };
  21812. /**
  21813. * Returns a positive integer : the total number of indices in this mesh geometry.
  21814. * Returns zero if the mesh has no geometry.
  21815. */
  21816. Mesh.prototype.getTotalIndices = function () {
  21817. if (!this._geometry) {
  21818. return 0;
  21819. }
  21820. return this._geometry.getTotalIndices();
  21821. };
  21822. /**
  21823. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21824. * 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.
  21825. * Returns an empty array if the mesh has no geometry.
  21826. */
  21827. Mesh.prototype.getIndices = function (copyWhenShared) {
  21828. if (!this._geometry) {
  21829. return [];
  21830. }
  21831. return this._geometry.getIndices(copyWhenShared);
  21832. };
  21833. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21834. get: function () {
  21835. return this._masterMesh !== null && this._masterMesh !== undefined;
  21836. },
  21837. enumerable: true,
  21838. configurable: true
  21839. });
  21840. /**
  21841. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21842. */
  21843. Mesh.prototype.isReady = function () {
  21844. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21845. return false;
  21846. }
  21847. return _super.prototype.isReady.call(this);
  21848. };
  21849. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21850. /**
  21851. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21852. * This property is pertinent only for updatable parametric shapes.
  21853. */
  21854. get: function () {
  21855. return this._areNormalsFrozen;
  21856. },
  21857. enumerable: true,
  21858. configurable: true
  21859. });
  21860. /**
  21861. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21862. * It has no effect at all on other shapes.
  21863. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21864. * Returns the Mesh.
  21865. */
  21866. Mesh.prototype.freezeNormals = function () {
  21867. this._areNormalsFrozen = true;
  21868. return this;
  21869. };
  21870. /**
  21871. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21872. * It has no effect at all on other shapes.
  21873. * It reactivates the mesh normals computation if it was previously frozen.
  21874. * Returns the Mesh.
  21875. */
  21876. Mesh.prototype.unfreezeNormals = function () {
  21877. this._areNormalsFrozen = false;
  21878. return this;
  21879. };
  21880. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21881. /**
  21882. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21883. */
  21884. set: function (count) {
  21885. this._overridenInstanceCount = count;
  21886. },
  21887. enumerable: true,
  21888. configurable: true
  21889. });
  21890. // Methods
  21891. Mesh.prototype._preActivate = function () {
  21892. var sceneRenderId = this.getScene().getRenderId();
  21893. if (this._preActivateId === sceneRenderId) {
  21894. return this;
  21895. }
  21896. this._preActivateId = sceneRenderId;
  21897. this._visibleInstances = null;
  21898. return this;
  21899. };
  21900. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21901. if (this._visibleInstances) {
  21902. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21903. }
  21904. return this;
  21905. };
  21906. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21907. if (!this._visibleInstances) {
  21908. this._visibleInstances = {};
  21909. this._visibleInstances.defaultRenderId = renderId;
  21910. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21911. }
  21912. if (!this._visibleInstances[renderId]) {
  21913. this._visibleInstances[renderId] = new Array();
  21914. }
  21915. this._visibleInstances[renderId].push(instance);
  21916. return this;
  21917. };
  21918. /**
  21919. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21920. * This means the mesh underlying bounding box and sphere are recomputed.
  21921. * Returns the Mesh.
  21922. */
  21923. Mesh.prototype.refreshBoundingInfo = function () {
  21924. if (this._boundingInfo.isLocked) {
  21925. return;
  21926. }
  21927. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21928. if (data) {
  21929. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21930. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21931. }
  21932. if (this.subMeshes) {
  21933. for (var index = 0; index < this.subMeshes.length; index++) {
  21934. this.subMeshes[index].refreshBoundingInfo();
  21935. }
  21936. }
  21937. this._updateBoundingInfo();
  21938. return this;
  21939. };
  21940. Mesh.prototype._createGlobalSubMesh = function (force) {
  21941. var totalVertices = this.getTotalVertices();
  21942. if (!totalVertices || !this.getIndices()) {
  21943. return null;
  21944. }
  21945. // Check if we need to recreate the submeshes
  21946. if (this.subMeshes && this.subMeshes.length > 0) {
  21947. var totalIndices = this.getIndices().length;
  21948. var needToRecreate = false;
  21949. if (force) {
  21950. needToRecreate = true;
  21951. }
  21952. else {
  21953. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21954. var submesh = _a[_i];
  21955. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21956. needToRecreate = true;
  21957. break;
  21958. }
  21959. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21960. needToRecreate = true;
  21961. break;
  21962. }
  21963. }
  21964. }
  21965. if (!needToRecreate) {
  21966. return;
  21967. }
  21968. }
  21969. this.releaseSubMeshes();
  21970. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21971. };
  21972. Mesh.prototype.subdivide = function (count) {
  21973. if (count < 1) {
  21974. return;
  21975. }
  21976. var totalIndices = this.getTotalIndices();
  21977. var subdivisionSize = (totalIndices / count) | 0;
  21978. var offset = 0;
  21979. // Ensure that subdivisionSize is a multiple of 3
  21980. while (subdivisionSize % 3 !== 0) {
  21981. subdivisionSize++;
  21982. }
  21983. this.releaseSubMeshes();
  21984. for (var index = 0; index < count; index++) {
  21985. if (offset >= totalIndices) {
  21986. break;
  21987. }
  21988. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21989. offset += subdivisionSize;
  21990. }
  21991. this.synchronizeInstances();
  21992. };
  21993. /**
  21994. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21995. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21996. * The `data` are either a numeric array either a Float32Array.
  21997. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21998. * 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).
  21999. * Note that a new underlying VertexBuffer object is created each call.
  22000. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  22001. *
  22002. * Possible `kind` values :
  22003. * - BABYLON.VertexBuffer.PositionKind
  22004. * - BABYLON.VertexBuffer.UVKind
  22005. * - BABYLON.VertexBuffer.UV2Kind
  22006. * - BABYLON.VertexBuffer.UV3Kind
  22007. * - BABYLON.VertexBuffer.UV4Kind
  22008. * - BABYLON.VertexBuffer.UV5Kind
  22009. * - BABYLON.VertexBuffer.UV6Kind
  22010. * - BABYLON.VertexBuffer.ColorKind
  22011. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22012. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22013. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22014. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22015. *
  22016. * Returns the Mesh.
  22017. */
  22018. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22019. if (!this._geometry) {
  22020. var vertexData = new BABYLON.VertexData();
  22021. vertexData.set(data, kind);
  22022. var scene = this.getScene();
  22023. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22024. }
  22025. else {
  22026. this._geometry.setVerticesData(kind, data, updatable, stride);
  22027. }
  22028. return this;
  22029. };
  22030. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  22031. if (updatable === void 0) { updatable = true; }
  22032. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  22033. return;
  22034. }
  22035. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  22036. };
  22037. /**
  22038. * Sets the mesh VertexBuffer.
  22039. * Returns the Mesh.
  22040. */
  22041. Mesh.prototype.setVerticesBuffer = function (buffer) {
  22042. if (!this._geometry) {
  22043. var scene = this.getScene();
  22044. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  22045. }
  22046. this._geometry.setVerticesBuffer(buffer);
  22047. return this;
  22048. };
  22049. /**
  22050. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  22051. * If the mesh has no geometry, it is simply returned as it is.
  22052. * The `data` are either a numeric array either a Float32Array.
  22053. * No new underlying VertexBuffer object is created.
  22054. * 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.
  22055. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  22056. *
  22057. * Possible `kind` values :
  22058. * - BABYLON.VertexBuffer.PositionKind
  22059. * - BABYLON.VertexBuffer.UVKind
  22060. * - BABYLON.VertexBuffer.UV2Kind
  22061. * - BABYLON.VertexBuffer.UV3Kind
  22062. * - BABYLON.VertexBuffer.UV4Kind
  22063. * - BABYLON.VertexBuffer.UV5Kind
  22064. * - BABYLON.VertexBuffer.UV6Kind
  22065. * - BABYLON.VertexBuffer.ColorKind
  22066. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22067. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22068. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22069. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22070. *
  22071. * Returns the Mesh.
  22072. */
  22073. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  22074. if (!this._geometry) {
  22075. return;
  22076. }
  22077. if (!makeItUnique) {
  22078. this._geometry.updateVerticesData(kind, data, updateExtends);
  22079. }
  22080. else {
  22081. this.makeGeometryUnique();
  22082. this.updateVerticesData(kind, data, updateExtends, false);
  22083. }
  22084. return this;
  22085. };
  22086. /**
  22087. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  22088. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  22089. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  22090. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  22091. * Returns the Mesh.
  22092. */
  22093. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  22094. if (computeNormals === void 0) { computeNormals = true; }
  22095. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22096. positionFunction(positions);
  22097. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22098. if (computeNormals) {
  22099. var indices = this.getIndices();
  22100. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22101. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22102. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22103. }
  22104. return this;
  22105. };
  22106. /**
  22107. * Creates a un-shared specific occurence of the geometry for the mesh.
  22108. * Returns the Mesh.
  22109. */
  22110. Mesh.prototype.makeGeometryUnique = function () {
  22111. if (!this._geometry) {
  22112. return;
  22113. }
  22114. var oldGeometry = this._geometry;
  22115. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  22116. oldGeometry.releaseForMesh(this, true);
  22117. geometry.applyToMesh(this);
  22118. return this;
  22119. };
  22120. /**
  22121. * Sets the mesh indices.
  22122. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  22123. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  22124. * This method creates a new index buffer each call.
  22125. * Returns the Mesh.
  22126. */
  22127. Mesh.prototype.setIndices = function (indices, totalVertices) {
  22128. if (!this._geometry) {
  22129. var vertexData = new BABYLON.VertexData();
  22130. vertexData.indices = indices;
  22131. var scene = this.getScene();
  22132. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  22133. }
  22134. else {
  22135. this._geometry.setIndices(indices, totalVertices);
  22136. }
  22137. return this;
  22138. };
  22139. /**
  22140. * Invert the geometry to move from a right handed system to a left handed one.
  22141. * Returns the Mesh.
  22142. */
  22143. Mesh.prototype.toLeftHanded = function () {
  22144. if (!this._geometry) {
  22145. return;
  22146. }
  22147. this._geometry.toLeftHanded();
  22148. return this;
  22149. };
  22150. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  22151. var engine = this.getScene().getEngine();
  22152. // Wireframe
  22153. var indexToBind;
  22154. if (this._unIndexed) {
  22155. indexToBind = null;
  22156. }
  22157. else {
  22158. switch (fillMode) {
  22159. case BABYLON.Material.PointFillMode:
  22160. indexToBind = null;
  22161. break;
  22162. case BABYLON.Material.WireFrameFillMode:
  22163. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  22164. break;
  22165. default:
  22166. case BABYLON.Material.TriangleFillMode:
  22167. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  22168. break;
  22169. }
  22170. }
  22171. // VBOs
  22172. this._geometry._bind(effect, indexToBind);
  22173. return this;
  22174. };
  22175. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  22176. if (alternate === void 0) { alternate = false; }
  22177. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22178. return this;
  22179. }
  22180. this.onBeforeDrawObservable.notifyObservers(this);
  22181. var scene = this.getScene();
  22182. var engine = scene.getEngine();
  22183. // Draw order
  22184. switch (fillMode) {
  22185. case BABYLON.Material.PointFillMode:
  22186. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22187. break;
  22188. case BABYLON.Material.WireFrameFillMode:
  22189. if (this._unIndexed) {
  22190. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22191. }
  22192. else {
  22193. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  22194. }
  22195. break;
  22196. default:
  22197. if (this._unIndexed) {
  22198. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22199. }
  22200. else {
  22201. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  22202. }
  22203. }
  22204. if (scene._isAlternateRenderingEnabled && !alternate) {
  22205. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  22206. scene._switchToAlternateCameraConfiguration(true);
  22207. this._effectiveMaterial.bindView(effect);
  22208. this._effectiveMaterial.bindViewProjection(effect);
  22209. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  22210. this._draw(subMesh, fillMode, instancesCount, true);
  22211. engine.setViewport(scene.activeCamera.viewport);
  22212. scene._switchToAlternateCameraConfiguration(false);
  22213. this._effectiveMaterial.bindView(effect);
  22214. this._effectiveMaterial.bindViewProjection(effect);
  22215. }
  22216. return this;
  22217. };
  22218. /**
  22219. * Registers for this mesh a javascript function called just before the rendering process.
  22220. * This function is passed the current mesh.
  22221. * Return the Mesh.
  22222. */
  22223. Mesh.prototype.registerBeforeRender = function (func) {
  22224. this.onBeforeRenderObservable.add(func);
  22225. return this;
  22226. };
  22227. /**
  22228. * Disposes a previously registered javascript function called before the rendering.
  22229. * This function is passed the current mesh.
  22230. * Returns the Mesh.
  22231. */
  22232. Mesh.prototype.unregisterBeforeRender = function (func) {
  22233. this.onBeforeRenderObservable.removeCallback(func);
  22234. return this;
  22235. };
  22236. /**
  22237. * Registers for this mesh a javascript function called just after the rendering is complete.
  22238. * This function is passed the current mesh.
  22239. * Returns the Mesh.
  22240. */
  22241. Mesh.prototype.registerAfterRender = function (func) {
  22242. this.onAfterRenderObservable.add(func);
  22243. return this;
  22244. };
  22245. /**
  22246. * Disposes a previously registered javascript function called after the rendering.
  22247. * This function is passed the current mesh.
  22248. * Return the Mesh.
  22249. */
  22250. Mesh.prototype.unregisterAfterRender = function (func) {
  22251. this.onAfterRenderObservable.removeCallback(func);
  22252. return this;
  22253. };
  22254. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  22255. var scene = this.getScene();
  22256. this._batchCache.mustReturn = false;
  22257. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  22258. this._batchCache.visibleInstances[subMeshId] = null;
  22259. if (this._visibleInstances) {
  22260. var currentRenderId = scene.getRenderId();
  22261. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  22262. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  22263. var selfRenderId = this._renderId;
  22264. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  22265. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  22266. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  22267. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  22268. }
  22269. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  22270. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  22271. this._batchCache.mustReturn = true;
  22272. return this._batchCache;
  22273. }
  22274. if (currentRenderId !== selfRenderId) {
  22275. this._batchCache.renderSelf[subMeshId] = false;
  22276. }
  22277. }
  22278. this._renderIdForInstances[subMeshId] = currentRenderId;
  22279. }
  22280. return this._batchCache;
  22281. };
  22282. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  22283. var visibleInstances = batch.visibleInstances[subMesh._id];
  22284. var matricesCount = visibleInstances.length + 1;
  22285. var bufferSize = matricesCount * 16 * 4;
  22286. var currentInstancesBufferSize = this._instancesBufferSize;
  22287. var instancesBuffer = this._instancesBuffer;
  22288. while (this._instancesBufferSize < bufferSize) {
  22289. this._instancesBufferSize *= 2;
  22290. }
  22291. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  22292. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  22293. }
  22294. var offset = 0;
  22295. var instancesCount = 0;
  22296. var world = this.getWorldMatrix();
  22297. if (batch.renderSelf[subMesh._id]) {
  22298. world.copyToArray(this._instancesData, offset);
  22299. offset += 16;
  22300. instancesCount++;
  22301. }
  22302. if (visibleInstances) {
  22303. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  22304. var instance = visibleInstances[instanceIndex];
  22305. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  22306. offset += 16;
  22307. instancesCount++;
  22308. }
  22309. }
  22310. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  22311. if (instancesBuffer) {
  22312. instancesBuffer.dispose();
  22313. }
  22314. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  22315. this._instancesBuffer = instancesBuffer;
  22316. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  22317. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  22318. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  22319. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  22320. }
  22321. else {
  22322. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  22323. }
  22324. this._bind(subMesh, effect, fillMode);
  22325. this._draw(subMesh, fillMode, instancesCount);
  22326. engine.unbindInstanceAttributes();
  22327. return this;
  22328. };
  22329. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  22330. var scene = this.getScene();
  22331. var engine = scene.getEngine();
  22332. if (hardwareInstancedRendering) {
  22333. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  22334. }
  22335. else {
  22336. if (batch.renderSelf[subMesh._id]) {
  22337. // Draw
  22338. if (onBeforeDraw) {
  22339. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  22340. }
  22341. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  22342. }
  22343. if (batch.visibleInstances[subMesh._id]) {
  22344. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22345. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22346. // World
  22347. var world = instance.getWorldMatrix();
  22348. if (onBeforeDraw) {
  22349. onBeforeDraw(true, world, effectiveMaterial);
  22350. }
  22351. // Draw
  22352. this._draw(subMesh, fillMode);
  22353. }
  22354. }
  22355. }
  22356. return this;
  22357. };
  22358. /**
  22359. * Triggers the draw call for the mesh.
  22360. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  22361. * Returns the Mesh.
  22362. */
  22363. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  22364. this.checkOcclusionQuery();
  22365. if (this._isOccluded) {
  22366. return;
  22367. }
  22368. var scene = this.getScene();
  22369. // Managing instances
  22370. var batch = this._getInstancesRenderList(subMesh._id);
  22371. if (batch.mustReturn) {
  22372. return this;
  22373. }
  22374. // Checking geometry state
  22375. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22376. return this;
  22377. }
  22378. var callbackIndex;
  22379. this.onBeforeRenderObservable.notifyObservers(this);
  22380. var engine = scene.getEngine();
  22381. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22382. // Material
  22383. this._effectiveMaterial = subMesh.getMaterial();
  22384. if (!this._effectiveMaterial) {
  22385. return this;
  22386. }
  22387. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22388. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  22389. return this;
  22390. }
  22391. }
  22392. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  22393. return this;
  22394. }
  22395. // Alpha mode
  22396. if (enableAlphaMode) {
  22397. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  22398. }
  22399. // Outline - step 1
  22400. var savedDepthWrite = engine.getDepthWrite();
  22401. if (this.renderOutline) {
  22402. engine.setDepthWrite(false);
  22403. scene.getOutlineRenderer().render(subMesh, batch);
  22404. engine.setDepthWrite(savedDepthWrite);
  22405. }
  22406. var effect;
  22407. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22408. effect = subMesh.effect;
  22409. }
  22410. else {
  22411. effect = this._effectiveMaterial.getEffect();
  22412. }
  22413. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  22414. if (this._effectiveMaterial.forceDepthWrite) {
  22415. engine.setDepthWrite(true);
  22416. }
  22417. // Bind
  22418. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  22419. if (!hardwareInstancedRendering) {
  22420. this._bind(subMesh, effect, fillMode);
  22421. }
  22422. var world = this.getWorldMatrix();
  22423. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22424. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  22425. }
  22426. else {
  22427. this._effectiveMaterial.bind(world, this);
  22428. }
  22429. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  22430. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  22431. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  22432. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  22433. }
  22434. // Draw
  22435. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  22436. // Unbind
  22437. this._effectiveMaterial.unbind();
  22438. // Outline - step 2
  22439. if (this.renderOutline && savedDepthWrite) {
  22440. engine.setDepthWrite(true);
  22441. engine.setColorWrite(false);
  22442. scene.getOutlineRenderer().render(subMesh, batch);
  22443. engine.setColorWrite(true);
  22444. }
  22445. // Overlay
  22446. if (this.renderOverlay) {
  22447. var currentMode = engine.getAlphaMode();
  22448. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22449. scene.getOutlineRenderer().render(subMesh, batch, true);
  22450. engine.setAlphaMode(currentMode);
  22451. }
  22452. this.onAfterRenderObservable.notifyObservers(this);
  22453. return this;
  22454. };
  22455. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  22456. if (isInstance) {
  22457. effectiveMaterial.bindOnlyWorldMatrix(world);
  22458. }
  22459. return this;
  22460. };
  22461. /**
  22462. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  22463. */
  22464. Mesh.prototype.getEmittedParticleSystems = function () {
  22465. var results = new Array();
  22466. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22467. var particleSystem = this.getScene().particleSystems[index];
  22468. if (particleSystem.emitter === this) {
  22469. results.push(particleSystem);
  22470. }
  22471. }
  22472. return results;
  22473. };
  22474. /**
  22475. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  22476. */
  22477. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  22478. var results = new Array();
  22479. var descendants = this.getDescendants();
  22480. descendants.push(this);
  22481. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22482. var particleSystem = this.getScene().particleSystems[index];
  22483. var emitter = particleSystem.emitter;
  22484. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  22485. results.push(particleSystem);
  22486. }
  22487. }
  22488. return results;
  22489. };
  22490. Mesh.prototype._checkDelayState = function () {
  22491. var scene = this.getScene();
  22492. if (this._geometry) {
  22493. this._geometry.load(scene);
  22494. }
  22495. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22496. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22497. this._queueLoad(this, scene);
  22498. }
  22499. return this;
  22500. };
  22501. Mesh.prototype._queueLoad = function (mesh, scene) {
  22502. var _this = this;
  22503. scene._addPendingData(mesh);
  22504. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22505. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22506. if (data instanceof ArrayBuffer) {
  22507. _this._delayLoadingFunction(data, _this);
  22508. }
  22509. else {
  22510. _this._delayLoadingFunction(JSON.parse(data), _this);
  22511. }
  22512. _this.instances.forEach(function (instance) {
  22513. instance._syncSubMeshes();
  22514. });
  22515. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22516. scene._removePendingData(_this);
  22517. }, function () { }, scene.database, getBinaryData);
  22518. return this;
  22519. };
  22520. /**
  22521. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22522. */
  22523. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22524. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22525. return false;
  22526. }
  22527. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22528. return false;
  22529. }
  22530. this._checkDelayState();
  22531. return true;
  22532. };
  22533. /**
  22534. * Sets the mesh material by the material or multiMaterial `id` property.
  22535. * The material `id` is a string identifying the material or the multiMaterial.
  22536. * This method returns the Mesh.
  22537. */
  22538. Mesh.prototype.setMaterialByID = function (id) {
  22539. var materials = this.getScene().materials;
  22540. var index;
  22541. for (index = materials.length - 1; index > -1; index--) {
  22542. if (materials[index].id === id) {
  22543. this.material = materials[index];
  22544. return this;
  22545. }
  22546. }
  22547. // Multi
  22548. var multiMaterials = this.getScene().multiMaterials;
  22549. for (index = multiMaterials.length - 1; index > -1; index--) {
  22550. if (multiMaterials[index].id === id) {
  22551. this.material = multiMaterials[index];
  22552. return this;
  22553. }
  22554. }
  22555. return this;
  22556. };
  22557. /**
  22558. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22559. */
  22560. Mesh.prototype.getAnimatables = function () {
  22561. var results = [];
  22562. if (this.material) {
  22563. results.push(this.material);
  22564. }
  22565. if (this.skeleton) {
  22566. results.push(this.skeleton);
  22567. }
  22568. return results;
  22569. };
  22570. /**
  22571. * Modifies the mesh geometry according to the passed transformation matrix.
  22572. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22573. * The mesh normals are modified accordingly the same transformation.
  22574. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22575. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22576. * Returns the Mesh.
  22577. */
  22578. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22579. // Position
  22580. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22581. return this;
  22582. }
  22583. var submeshes = this.subMeshes.splice(0);
  22584. this._resetPointsArrayCache();
  22585. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22586. var temp = [];
  22587. var index;
  22588. for (index = 0; index < data.length; index += 3) {
  22589. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22590. }
  22591. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22592. // Normals
  22593. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22594. return this;
  22595. }
  22596. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22597. temp = [];
  22598. for (index = 0; index < data.length; index += 3) {
  22599. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22600. }
  22601. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22602. // flip faces?
  22603. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22604. this.flipFaces();
  22605. }
  22606. // Restore submeshes
  22607. this.releaseSubMeshes();
  22608. this.subMeshes = submeshes;
  22609. return this;
  22610. };
  22611. /**
  22612. * Modifies the mesh geometry according to its own current World Matrix.
  22613. * The mesh World Matrix is then reset.
  22614. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22615. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22616. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22617. * Returns the Mesh.
  22618. */
  22619. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22620. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22621. this.scaling.copyFromFloats(1, 1, 1);
  22622. this.position.copyFromFloats(0, 0, 0);
  22623. this.rotation.copyFromFloats(0, 0, 0);
  22624. //only if quaternion is already set
  22625. if (this.rotationQuaternion) {
  22626. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22627. }
  22628. this._worldMatrix = BABYLON.Matrix.Identity();
  22629. return this;
  22630. };
  22631. Object.defineProperty(Mesh.prototype, "_positions", {
  22632. // Cache
  22633. get: function () {
  22634. if (this._geometry) {
  22635. return this._geometry._positions;
  22636. }
  22637. return null;
  22638. },
  22639. enumerable: true,
  22640. configurable: true
  22641. });
  22642. Mesh.prototype._resetPointsArrayCache = function () {
  22643. if (this._geometry) {
  22644. this._geometry._resetPointsArrayCache();
  22645. }
  22646. return this;
  22647. };
  22648. Mesh.prototype._generatePointsArray = function () {
  22649. if (this._geometry) {
  22650. return this._geometry._generatePointsArray();
  22651. }
  22652. return false;
  22653. };
  22654. /**
  22655. * Returns a new Mesh object generated from the current mesh properties.
  22656. * This method must not get confused with createInstance().
  22657. * The parameter `name` is a string, the name given to the new mesh.
  22658. * The optional parameter `newParent` can be any Node object (default `null`).
  22659. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22660. * 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.
  22661. */
  22662. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22663. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22664. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22665. };
  22666. /**
  22667. * Disposes the mesh.
  22668. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22669. */
  22670. Mesh.prototype.dispose = function (doNotRecurse) {
  22671. var _this = this;
  22672. this.morphTargetManager = undefined;
  22673. if (this._geometry) {
  22674. this._geometry.releaseForMesh(this, true);
  22675. }
  22676. // Sources
  22677. var meshes = this.getScene().meshes;
  22678. meshes.forEach(function (mesh) {
  22679. if (mesh._source && mesh._source === _this) {
  22680. mesh._source = null;
  22681. }
  22682. });
  22683. this._source = null;
  22684. // Instances
  22685. if (this._instancesBuffer) {
  22686. this._instancesBuffer.dispose();
  22687. this._instancesBuffer = null;
  22688. }
  22689. while (this.instances.length) {
  22690. this.instances[0].dispose();
  22691. }
  22692. // Highlight layers.
  22693. var highlightLayers = this.getScene().highlightLayers;
  22694. for (var i = 0; i < highlightLayers.length; i++) {
  22695. var highlightLayer = highlightLayers[i];
  22696. if (highlightLayer) {
  22697. highlightLayer.removeMesh(this);
  22698. highlightLayer.removeExcludedMesh(this);
  22699. }
  22700. }
  22701. _super.prototype.dispose.call(this, doNotRecurse);
  22702. };
  22703. /**
  22704. * Modifies the mesh geometry according to a displacement map.
  22705. * 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.
  22706. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22707. * This method returns nothing.
  22708. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22709. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22710. * 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.
  22711. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22712. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22713. *
  22714. * Returns the Mesh.
  22715. */
  22716. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22717. var _this = this;
  22718. var scene = this.getScene();
  22719. var onload = function (img) {
  22720. // Getting height map data
  22721. var canvas = document.createElement("canvas");
  22722. var context = canvas.getContext("2d");
  22723. var heightMapWidth = img.width;
  22724. var heightMapHeight = img.height;
  22725. canvas.width = heightMapWidth;
  22726. canvas.height = heightMapHeight;
  22727. context.drawImage(img, 0, 0);
  22728. // Create VertexData from map data
  22729. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22730. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22731. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22732. //execute success callback, if set
  22733. if (onSuccess) {
  22734. onSuccess(_this);
  22735. }
  22736. };
  22737. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22738. return this;
  22739. };
  22740. /**
  22741. * Modifies the mesh geometry according to a displacementMap buffer.
  22742. * 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.
  22743. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22744. * This method returns nothing.
  22745. * 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.
  22746. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22747. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22748. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22749. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22750. *
  22751. * Returns the Mesh.
  22752. */
  22753. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22754. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22755. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22756. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22757. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22758. return this;
  22759. }
  22760. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22761. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22762. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22763. var position = BABYLON.Vector3.Zero();
  22764. var normal = BABYLON.Vector3.Zero();
  22765. var uv = BABYLON.Vector2.Zero();
  22766. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22767. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22768. for (var index = 0; index < positions.length; index += 3) {
  22769. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22770. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22771. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22772. // Compute height
  22773. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22774. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22775. var pos = (u + v * heightMapWidth) * 4;
  22776. var r = buffer[pos] / 255.0;
  22777. var g = buffer[pos + 1] / 255.0;
  22778. var b = buffer[pos + 2] / 255.0;
  22779. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22780. normal.normalize();
  22781. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22782. position = position.add(normal);
  22783. position.toArray(positions, index);
  22784. }
  22785. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22786. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22787. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22788. return this;
  22789. };
  22790. /**
  22791. * Modify the mesh to get a flat shading rendering.
  22792. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22793. * This method returns the Mesh.
  22794. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22795. */
  22796. Mesh.prototype.convertToFlatShadedMesh = function () {
  22797. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22798. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22799. var kinds = this.getVerticesDataKinds();
  22800. var vbs = [];
  22801. var data = [];
  22802. var newdata = [];
  22803. var updatableNormals = false;
  22804. var kindIndex;
  22805. var kind;
  22806. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22807. kind = kinds[kindIndex];
  22808. var vertexBuffer = this.getVertexBuffer(kind);
  22809. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22810. updatableNormals = vertexBuffer.isUpdatable();
  22811. kinds.splice(kindIndex, 1);
  22812. kindIndex--;
  22813. continue;
  22814. }
  22815. vbs[kind] = vertexBuffer;
  22816. data[kind] = vbs[kind].getData();
  22817. newdata[kind] = [];
  22818. }
  22819. // Save previous submeshes
  22820. var previousSubmeshes = this.subMeshes.slice(0);
  22821. var indices = this.getIndices();
  22822. var totalIndices = this.getTotalIndices();
  22823. // Generating unique vertices per face
  22824. var index;
  22825. for (index = 0; index < totalIndices; index++) {
  22826. var vertexIndex = indices[index];
  22827. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22828. kind = kinds[kindIndex];
  22829. var stride = vbs[kind].getStrideSize();
  22830. for (var offset = 0; offset < stride; offset++) {
  22831. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22832. }
  22833. }
  22834. }
  22835. // Updating faces & normal
  22836. var normals = [];
  22837. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22838. for (index = 0; index < totalIndices; index += 3) {
  22839. indices[index] = index;
  22840. indices[index + 1] = index + 1;
  22841. indices[index + 2] = index + 2;
  22842. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22843. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22844. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22845. var p1p2 = p1.subtract(p2);
  22846. var p3p2 = p3.subtract(p2);
  22847. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22848. // Store same normals for every vertex
  22849. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22850. normals.push(normal.x);
  22851. normals.push(normal.y);
  22852. normals.push(normal.z);
  22853. }
  22854. }
  22855. this.setIndices(indices);
  22856. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22857. // Updating vertex buffers
  22858. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22859. kind = kinds[kindIndex];
  22860. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22861. }
  22862. // Updating submeshes
  22863. this.releaseSubMeshes();
  22864. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22865. var previousOne = previousSubmeshes[submeshIndex];
  22866. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22867. }
  22868. this.synchronizeInstances();
  22869. return this;
  22870. };
  22871. /**
  22872. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22873. * In other words, more vertices, no more indices and a single bigger VBO.
  22874. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22875. * Returns the Mesh.
  22876. */
  22877. Mesh.prototype.convertToUnIndexedMesh = function () {
  22878. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22879. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22880. var kinds = this.getVerticesDataKinds();
  22881. var vbs = [];
  22882. var data = [];
  22883. var newdata = [];
  22884. var updatableNormals = false;
  22885. var kindIndex;
  22886. var kind;
  22887. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22888. kind = kinds[kindIndex];
  22889. var vertexBuffer = this.getVertexBuffer(kind);
  22890. vbs[kind] = vertexBuffer;
  22891. data[kind] = vbs[kind].getData();
  22892. newdata[kind] = [];
  22893. }
  22894. // Save previous submeshes
  22895. var previousSubmeshes = this.subMeshes.slice(0);
  22896. var indices = this.getIndices();
  22897. var totalIndices = this.getTotalIndices();
  22898. // Generating unique vertices per face
  22899. var index;
  22900. for (index = 0; index < totalIndices; index++) {
  22901. var vertexIndex = indices[index];
  22902. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22903. kind = kinds[kindIndex];
  22904. var stride = vbs[kind].getStrideSize();
  22905. for (var offset = 0; offset < stride; offset++) {
  22906. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22907. }
  22908. }
  22909. }
  22910. // Updating indices
  22911. for (index = 0; index < totalIndices; index += 3) {
  22912. indices[index] = index;
  22913. indices[index + 1] = index + 1;
  22914. indices[index + 2] = index + 2;
  22915. }
  22916. this.setIndices(indices);
  22917. // Updating vertex buffers
  22918. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22919. kind = kinds[kindIndex];
  22920. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22921. }
  22922. // Updating submeshes
  22923. this.releaseSubMeshes();
  22924. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22925. var previousOne = previousSubmeshes[submeshIndex];
  22926. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22927. }
  22928. this._unIndexed = true;
  22929. this.synchronizeInstances();
  22930. return this;
  22931. };
  22932. /**
  22933. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22934. * This method returns the Mesh.
  22935. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22936. */
  22937. Mesh.prototype.flipFaces = function (flipNormals) {
  22938. if (flipNormals === void 0) { flipNormals = false; }
  22939. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22940. var i;
  22941. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22942. for (i = 0; i < vertex_data.normals.length; i++) {
  22943. vertex_data.normals[i] *= -1;
  22944. }
  22945. }
  22946. var temp;
  22947. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22948. // reassign indices
  22949. temp = vertex_data.indices[i + 1];
  22950. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22951. vertex_data.indices[i + 2] = temp;
  22952. }
  22953. vertex_data.applyToMesh(this);
  22954. return this;
  22955. };
  22956. // Instances
  22957. /**
  22958. * Creates a new InstancedMesh object from the mesh model.
  22959. * An instance shares the same properties and the same material than its model.
  22960. * Only these properties of each instance can then be set individually :
  22961. * - position
  22962. * - rotation
  22963. * - rotationQuaternion
  22964. * - setPivotMatrix
  22965. * - scaling
  22966. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22967. * Warning : this method is not supported for Line mesh and LineSystem
  22968. */
  22969. Mesh.prototype.createInstance = function (name) {
  22970. return new BABYLON.InstancedMesh(name, this);
  22971. };
  22972. /**
  22973. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22974. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22975. * This method returns the Mesh.
  22976. */
  22977. Mesh.prototype.synchronizeInstances = function () {
  22978. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22979. var instance = this.instances[instanceIndex];
  22980. instance._syncSubMeshes();
  22981. }
  22982. return this;
  22983. };
  22984. /**
  22985. * Simplify the mesh according to the given array of settings.
  22986. * Function will return immediately and will simplify async. It returns the Mesh.
  22987. * @param settings a collection of simplification settings.
  22988. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22989. * @param type the type of simplification to run.
  22990. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22991. */
  22992. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22993. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22994. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22995. this.getScene().simplificationQueue.addTask({
  22996. settings: settings,
  22997. parallelProcessing: parallelProcessing,
  22998. mesh: this,
  22999. simplificationType: simplificationType,
  23000. successCallback: successCallback
  23001. });
  23002. return this;
  23003. };
  23004. /**
  23005. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  23006. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  23007. * This should be used together with the simplification to avoid disappearing triangles.
  23008. * Returns the Mesh.
  23009. * @param successCallback an optional success callback to be called after the optimization finished.
  23010. */
  23011. Mesh.prototype.optimizeIndices = function (successCallback) {
  23012. var _this = this;
  23013. var indices = this.getIndices();
  23014. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23015. var vectorPositions = [];
  23016. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  23017. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  23018. }
  23019. var dupes = [];
  23020. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  23021. var realPos = vectorPositions.length - 1 - iteration;
  23022. var testedPosition = vectorPositions[realPos];
  23023. for (var j = 0; j < realPos; ++j) {
  23024. var againstPosition = vectorPositions[j];
  23025. if (testedPosition.equals(againstPosition)) {
  23026. dupes[realPos] = j;
  23027. break;
  23028. }
  23029. }
  23030. }, function () {
  23031. for (var i = 0; i < indices.length; ++i) {
  23032. indices[i] = dupes[indices[i]] || indices[i];
  23033. }
  23034. //indices are now reordered
  23035. var originalSubMeshes = _this.subMeshes.slice(0);
  23036. _this.setIndices(indices);
  23037. _this.subMeshes = originalSubMeshes;
  23038. if (successCallback) {
  23039. successCallback(_this);
  23040. }
  23041. });
  23042. return this;
  23043. };
  23044. Mesh.prototype.serialize = function (serializationObject) {
  23045. serializationObject.name = this.name;
  23046. serializationObject.id = this.id;
  23047. serializationObject.type = this.getClassName();
  23048. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  23049. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23050. }
  23051. serializationObject.position = this.position.asArray();
  23052. if (this.rotationQuaternion) {
  23053. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  23054. }
  23055. else if (this.rotation) {
  23056. serializationObject.rotation = this.rotation.asArray();
  23057. }
  23058. serializationObject.scaling = this.scaling.asArray();
  23059. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  23060. serializationObject.isEnabled = this.isEnabled();
  23061. serializationObject.isVisible = this.isVisible;
  23062. serializationObject.infiniteDistance = this.infiniteDistance;
  23063. serializationObject.pickable = this.isPickable;
  23064. serializationObject.receiveShadows = this.receiveShadows;
  23065. serializationObject.billboardMode = this.billboardMode;
  23066. serializationObject.visibility = this.visibility;
  23067. serializationObject.checkCollisions = this.checkCollisions;
  23068. serializationObject.isBlocker = this.isBlocker;
  23069. // Parent
  23070. if (this.parent) {
  23071. serializationObject.parentId = this.parent.id;
  23072. }
  23073. // Geometry
  23074. var geometry = this._geometry;
  23075. if (geometry) {
  23076. var geometryId = geometry.id;
  23077. serializationObject.geometryId = geometryId;
  23078. // SubMeshes
  23079. serializationObject.subMeshes = [];
  23080. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  23081. var subMesh = this.subMeshes[subIndex];
  23082. serializationObject.subMeshes.push({
  23083. materialIndex: subMesh.materialIndex,
  23084. verticesStart: subMesh.verticesStart,
  23085. verticesCount: subMesh.verticesCount,
  23086. indexStart: subMesh.indexStart,
  23087. indexCount: subMesh.indexCount
  23088. });
  23089. }
  23090. }
  23091. // Material
  23092. if (this.material) {
  23093. serializationObject.materialId = this.material.id;
  23094. }
  23095. else {
  23096. this.material = null;
  23097. }
  23098. // Morph targets
  23099. if (this.morphTargetManager) {
  23100. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  23101. }
  23102. // Skeleton
  23103. if (this.skeleton) {
  23104. serializationObject.skeletonId = this.skeleton.id;
  23105. }
  23106. // Physics
  23107. //TODO implement correct serialization for physics impostors.
  23108. if (this.getPhysicsImpostor()) {
  23109. var impostor = this.getPhysicsImpostor();
  23110. serializationObject.physicsMass = impostor.getParam("mass");
  23111. serializationObject.physicsFriction = impostor.getParam("friction");
  23112. serializationObject.physicsRestitution = impostor.getParam("mass");
  23113. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  23114. }
  23115. // Metadata
  23116. if (this.metadata) {
  23117. serializationObject.metadata = this.metadata;
  23118. }
  23119. // Instances
  23120. serializationObject.instances = [];
  23121. for (var index = 0; index < this.instances.length; index++) {
  23122. var instance = this.instances[index];
  23123. var serializationInstance = {
  23124. name: instance.name,
  23125. position: instance.position.asArray(),
  23126. scaling: instance.scaling.asArray()
  23127. };
  23128. if (instance.rotationQuaternion) {
  23129. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  23130. }
  23131. else if (instance.rotation) {
  23132. serializationInstance.rotation = instance.rotation.asArray();
  23133. }
  23134. serializationObject.instances.push(serializationInstance);
  23135. // Animations
  23136. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  23137. serializationInstance.ranges = instance.serializeAnimationRanges();
  23138. }
  23139. //
  23140. // Animations
  23141. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23142. serializationObject.ranges = this.serializeAnimationRanges();
  23143. // Layer mask
  23144. serializationObject.layerMask = this.layerMask;
  23145. // Alpha
  23146. serializationObject.alphaIndex = this.alphaIndex;
  23147. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  23148. // Overlay
  23149. serializationObject.overlayAlpha = this.overlayAlpha;
  23150. serializationObject.overlayColor = this.overlayColor.asArray();
  23151. serializationObject.renderOverlay = this.renderOverlay;
  23152. // Fog
  23153. serializationObject.applyFog = this.applyFog;
  23154. // Action Manager
  23155. if (this.actionManager) {
  23156. serializationObject.actions = this.actionManager.serialize(this.name);
  23157. }
  23158. };
  23159. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  23160. if (!this.geometry) {
  23161. return;
  23162. }
  23163. this._markSubMeshesAsAttributesDirty();
  23164. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  23165. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  23166. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  23167. this.morphTargetManager = undefined;
  23168. return;
  23169. }
  23170. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  23171. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  23172. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  23173. if (morphTarget.hasNormals) {
  23174. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  23175. }
  23176. if (morphTarget.hasTangents) {
  23177. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  23178. }
  23179. }
  23180. }
  23181. else {
  23182. var index = 0;
  23183. // Positions
  23184. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  23185. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  23186. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  23187. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  23188. }
  23189. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  23190. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  23191. }
  23192. index++;
  23193. }
  23194. }
  23195. };
  23196. // Statics
  23197. /**
  23198. * Returns a new Mesh object what is a deep copy of the passed mesh.
  23199. * The parameter `parsedMesh` is the mesh to be copied.
  23200. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  23201. */
  23202. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  23203. var mesh;
  23204. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  23205. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  23206. }
  23207. else {
  23208. mesh = new Mesh(parsedMesh.name, scene);
  23209. }
  23210. mesh.id = parsedMesh.id;
  23211. if (BABYLON.Tags) {
  23212. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  23213. }
  23214. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  23215. if (parsedMesh.metadata !== undefined) {
  23216. mesh.metadata = parsedMesh.metadata;
  23217. }
  23218. if (parsedMesh.rotationQuaternion) {
  23219. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  23220. }
  23221. else if (parsedMesh.rotation) {
  23222. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  23223. }
  23224. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  23225. if (parsedMesh.localMatrix) {
  23226. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  23227. }
  23228. else if (parsedMesh.pivotMatrix) {
  23229. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  23230. }
  23231. mesh.setEnabled(parsedMesh.isEnabled);
  23232. mesh.isVisible = parsedMesh.isVisible;
  23233. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  23234. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  23235. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  23236. if (parsedMesh.applyFog !== undefined) {
  23237. mesh.applyFog = parsedMesh.applyFog;
  23238. }
  23239. if (parsedMesh.pickable !== undefined) {
  23240. mesh.isPickable = parsedMesh.pickable;
  23241. }
  23242. if (parsedMesh.alphaIndex !== undefined) {
  23243. mesh.alphaIndex = parsedMesh.alphaIndex;
  23244. }
  23245. mesh.receiveShadows = parsedMesh.receiveShadows;
  23246. mesh.billboardMode = parsedMesh.billboardMode;
  23247. if (parsedMesh.visibility !== undefined) {
  23248. mesh.visibility = parsedMesh.visibility;
  23249. }
  23250. mesh.checkCollisions = parsedMesh.checkCollisions;
  23251. if (parsedMesh.isBlocker !== undefined) {
  23252. mesh.isBlocker = parsedMesh.isBlocker;
  23253. }
  23254. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  23255. // freezeWorldMatrix
  23256. if (parsedMesh.freezeWorldMatrix) {
  23257. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  23258. }
  23259. // Parent
  23260. if (parsedMesh.parentId) {
  23261. mesh._waitingParentId = parsedMesh.parentId;
  23262. }
  23263. // Actions
  23264. if (parsedMesh.actions !== undefined) {
  23265. mesh._waitingActions = parsedMesh.actions;
  23266. }
  23267. // Overlay
  23268. if (parsedMesh.overlayAlpha !== undefined) {
  23269. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  23270. }
  23271. if (parsedMesh.overlayColor !== undefined) {
  23272. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  23273. }
  23274. if (parsedMesh.renderOverlay !== undefined) {
  23275. mesh.renderOverlay = parsedMesh.renderOverlay;
  23276. }
  23277. // Geometry
  23278. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  23279. if (parsedMesh.delayLoadingFile) {
  23280. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23281. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  23282. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  23283. if (parsedMesh._binaryInfo) {
  23284. mesh._binaryInfo = parsedMesh._binaryInfo;
  23285. }
  23286. mesh._delayInfo = [];
  23287. if (parsedMesh.hasUVs) {
  23288. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  23289. }
  23290. if (parsedMesh.hasUVs2) {
  23291. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  23292. }
  23293. if (parsedMesh.hasUVs3) {
  23294. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  23295. }
  23296. if (parsedMesh.hasUVs4) {
  23297. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  23298. }
  23299. if (parsedMesh.hasUVs5) {
  23300. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  23301. }
  23302. if (parsedMesh.hasUVs6) {
  23303. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  23304. }
  23305. if (parsedMesh.hasColors) {
  23306. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  23307. }
  23308. if (parsedMesh.hasMatricesIndices) {
  23309. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23310. }
  23311. if (parsedMesh.hasMatricesWeights) {
  23312. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23313. }
  23314. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  23315. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  23316. mesh._checkDelayState();
  23317. }
  23318. }
  23319. else {
  23320. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  23321. }
  23322. // Material
  23323. if (parsedMesh.materialId) {
  23324. mesh.setMaterialByID(parsedMesh.materialId);
  23325. }
  23326. else {
  23327. mesh.material = null;
  23328. }
  23329. // Morph targets
  23330. if (parsedMesh.morphTargetManagerId > -1) {
  23331. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  23332. }
  23333. // Skeleton
  23334. if (parsedMesh.skeletonId > -1) {
  23335. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  23336. if (parsedMesh.numBoneInfluencers) {
  23337. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  23338. }
  23339. }
  23340. // Animations
  23341. if (parsedMesh.animations) {
  23342. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23343. var parsedAnimation = parsedMesh.animations[animationIndex];
  23344. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23345. }
  23346. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  23347. }
  23348. if (parsedMesh.autoAnimate) {
  23349. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23350. }
  23351. // Layer Mask
  23352. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23353. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23354. }
  23355. else {
  23356. mesh.layerMask = 0x0FFFFFFF;
  23357. }
  23358. // Physics
  23359. if (parsedMesh.physicsImpostor) {
  23360. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23361. mass: parsedMesh.physicsMass,
  23362. friction: parsedMesh.physicsFriction,
  23363. restitution: parsedMesh.physicsRestitution
  23364. }, scene);
  23365. }
  23366. // Instances
  23367. if (parsedMesh.instances) {
  23368. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23369. var parsedInstance = parsedMesh.instances[index];
  23370. var instance = mesh.createInstance(parsedInstance.name);
  23371. if (BABYLON.Tags) {
  23372. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23373. }
  23374. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23375. if (parsedInstance.parentId) {
  23376. instance._waitingParentId = parsedInstance.parentId;
  23377. }
  23378. if (parsedInstance.rotationQuaternion) {
  23379. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23380. }
  23381. else if (parsedInstance.rotation) {
  23382. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  23383. }
  23384. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  23385. instance.checkCollisions = mesh.checkCollisions;
  23386. if (parsedMesh.animations) {
  23387. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23388. parsedAnimation = parsedMesh.animations[animationIndex];
  23389. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23390. }
  23391. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  23392. }
  23393. }
  23394. }
  23395. return mesh;
  23396. };
  23397. /**
  23398. * Creates a ribbon mesh.
  23399. * Please consider using the same method from the MeshBuilder class instead.
  23400. * 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.
  23401. *
  23402. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23403. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23404. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23405. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23406. * 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.
  23407. * 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.
  23408. * 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
  23409. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23410. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23411. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23412. */
  23413. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  23414. return BABYLON.MeshBuilder.CreateRibbon(name, {
  23415. pathArray: pathArray,
  23416. closeArray: closeArray,
  23417. closePath: closePath,
  23418. offset: offset,
  23419. updatable: updatable,
  23420. sideOrientation: sideOrientation,
  23421. instance: instance
  23422. }, scene);
  23423. };
  23424. /**
  23425. * Creates a plane polygonal mesh. By default, this is a disc.
  23426. * Please consider using the same method from the MeshBuilder class instead.
  23427. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23428. * 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.
  23429. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23430. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23432. */
  23433. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  23434. var options = {
  23435. radius: radius,
  23436. tessellation: tessellation,
  23437. sideOrientation: sideOrientation,
  23438. updatable: updatable
  23439. };
  23440. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  23441. };
  23442. /**
  23443. * Creates a box mesh.
  23444. * Please consider using the same method from the MeshBuilder class instead.
  23445. * The parameter `size` sets the size (float) of each box side (default 1).
  23446. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23447. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23448. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23449. */
  23450. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  23451. var options = {
  23452. size: size,
  23453. sideOrientation: sideOrientation,
  23454. updatable: updatable
  23455. };
  23456. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  23457. };
  23458. /**
  23459. * Creates a sphere mesh.
  23460. * Please consider using the same method from the MeshBuilder class instead.
  23461. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  23462. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  23463. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23464. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23465. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23466. */
  23467. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  23468. var options = {
  23469. segments: segments,
  23470. diameterX: diameter,
  23471. diameterY: diameter,
  23472. diameterZ: diameter,
  23473. sideOrientation: sideOrientation,
  23474. updatable: updatable
  23475. };
  23476. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  23477. };
  23478. /**
  23479. * Creates a cylinder or a cone mesh.
  23480. * Please consider using the same method from the MeshBuilder class instead.
  23481. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23482. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23483. * 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.
  23484. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23485. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23486. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23487. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23488. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23489. */
  23490. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23491. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23492. if (scene !== undefined) {
  23493. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23494. updatable = scene;
  23495. }
  23496. scene = subdivisions;
  23497. subdivisions = 1;
  23498. }
  23499. var options = {
  23500. height: height,
  23501. diameterTop: diameterTop,
  23502. diameterBottom: diameterBottom,
  23503. tessellation: tessellation,
  23504. subdivisions: subdivisions,
  23505. sideOrientation: sideOrientation,
  23506. updatable: updatable
  23507. };
  23508. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23509. };
  23510. // Torus (Code from SharpDX.org)
  23511. /**
  23512. * Creates a torus mesh.
  23513. * Please consider using the same method from the MeshBuilder class instead.
  23514. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23515. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23516. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23517. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23518. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23519. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23520. */
  23521. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23522. var options = {
  23523. diameter: diameter,
  23524. thickness: thickness,
  23525. tessellation: tessellation,
  23526. sideOrientation: sideOrientation,
  23527. updatable: updatable
  23528. };
  23529. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23530. };
  23531. /**
  23532. * Creates a torus knot mesh.
  23533. * Please consider using the same method from the MeshBuilder class instead.
  23534. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23535. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23536. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23537. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23538. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23539. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23540. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23541. */
  23542. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23543. var options = {
  23544. radius: radius,
  23545. tube: tube,
  23546. radialSegments: radialSegments,
  23547. tubularSegments: tubularSegments,
  23548. p: p,
  23549. q: q,
  23550. sideOrientation: sideOrientation,
  23551. updatable: updatable
  23552. };
  23553. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23554. };
  23555. /**
  23556. * Creates a line mesh.
  23557. * Please consider using the same method from the MeshBuilder class instead.
  23558. * 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.
  23559. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23560. * The parameter `points` is an array successive Vector3.
  23561. * 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
  23562. * When updating an instance, remember that only point positions can change, not the number of points.
  23563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23564. */
  23565. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23566. var options = {
  23567. points: points,
  23568. updatable: updatable,
  23569. instance: instance
  23570. };
  23571. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23572. };
  23573. /**
  23574. * Creates a dashed line mesh.
  23575. * Please consider using the same method from the MeshBuilder class instead.
  23576. * 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.
  23577. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23578. * The parameter `points` is an array successive Vector3.
  23579. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23580. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23581. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23582. * 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
  23583. * When updating an instance, remember that only point positions can change, not the number of points.
  23584. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23585. */
  23586. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23587. var options = {
  23588. points: points,
  23589. dashSize: dashSize,
  23590. gapSize: gapSize,
  23591. dashNb: dashNb,
  23592. updatable: updatable,
  23593. instance: instance
  23594. };
  23595. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23596. };
  23597. /**
  23598. * Creates a polygon mesh.
  23599. * Please consider using the same method from the MeshBuilder class instead.
  23600. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23601. * 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.
  23602. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23603. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23604. * Remember you can only change the shape positions, not their number when updating a polygon.
  23605. */
  23606. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23607. var options = {
  23608. shape: shape,
  23609. holes: holes,
  23610. updatable: updatable,
  23611. sideOrientation: sideOrientation
  23612. };
  23613. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23614. };
  23615. /**
  23616. * Creates an extruded polygon mesh, with depth in the Y direction.
  23617. * Please consider using the same method from the MeshBuilder class instead.
  23618. */
  23619. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23620. var options = {
  23621. shape: shape,
  23622. holes: holes,
  23623. depth: depth,
  23624. updatable: updatable,
  23625. sideOrientation: sideOrientation
  23626. };
  23627. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23628. };
  23629. /**
  23630. * Creates an extruded shape mesh.
  23631. * 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.
  23632. * Please consider using the same method from the MeshBuilder class instead.
  23633. *
  23634. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23635. * 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
  23636. * extruded along the Z axis.
  23637. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23638. * 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.
  23639. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23640. * 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
  23641. * 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
  23642. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23643. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23644. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23645. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23646. */
  23647. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23648. var options = {
  23649. shape: shape,
  23650. path: path,
  23651. scale: scale,
  23652. rotation: rotation,
  23653. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23654. sideOrientation: sideOrientation,
  23655. instance: instance,
  23656. updatable: updatable
  23657. };
  23658. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23659. };
  23660. /**
  23661. * Creates an custom extruded shape mesh.
  23662. * 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.
  23663. * Please consider using the same method from the MeshBuilder class instead.
  23664. *
  23665. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23666. * 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
  23667. * extruded along the Z axis.
  23668. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23669. * 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
  23670. * and the distance of this point from the begining of the path :
  23671. * ```javascript
  23672. * var rotationFunction = function(i, distance) {
  23673. * // do things
  23674. * return rotationValue; }
  23675. * ```
  23676. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23677. * 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
  23678. * and the distance of this point from the begining of the path :
  23679. * ```javascript
  23680. * var scaleFunction = function(i, distance) {
  23681. * // do things
  23682. * return scaleValue;}
  23683. * ```
  23684. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23685. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23686. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23687. * 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
  23688. * 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
  23689. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23690. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23691. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23693. */
  23694. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23695. var options = {
  23696. shape: shape,
  23697. path: path,
  23698. scaleFunction: scaleFunction,
  23699. rotationFunction: rotationFunction,
  23700. ribbonCloseArray: ribbonCloseArray,
  23701. ribbonClosePath: ribbonClosePath,
  23702. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23703. sideOrientation: sideOrientation,
  23704. instance: instance,
  23705. updatable: updatable
  23706. };
  23707. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23708. };
  23709. /**
  23710. * Creates lathe mesh.
  23711. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23712. * Please consider using the same method from the MeshBuilder class instead.
  23713. * 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
  23714. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23715. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23716. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23717. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23718. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23719. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23720. */
  23721. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23722. var options = {
  23723. shape: shape,
  23724. radius: radius,
  23725. tessellation: tessellation,
  23726. sideOrientation: sideOrientation,
  23727. updatable: updatable
  23728. };
  23729. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23730. };
  23731. /**
  23732. * Creates a plane mesh.
  23733. * Please consider using the same method from the MeshBuilder class instead.
  23734. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23735. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23736. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23737. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23738. */
  23739. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23740. var options = {
  23741. size: size,
  23742. width: size,
  23743. height: size,
  23744. sideOrientation: sideOrientation,
  23745. updatable: updatable
  23746. };
  23747. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23748. };
  23749. /**
  23750. * Creates a ground mesh.
  23751. * Please consider using the same method from the MeshBuilder class instead.
  23752. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23753. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23754. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23755. */
  23756. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23757. var options = {
  23758. width: width,
  23759. height: height,
  23760. subdivisions: subdivisions,
  23761. updatable: updatable
  23762. };
  23763. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23764. };
  23765. /**
  23766. * Creates a tiled ground mesh.
  23767. * Please consider using the same method from the MeshBuilder class instead.
  23768. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23769. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23770. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23771. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23772. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23773. * numbers of subdivisions on the ground width and height of each tile.
  23774. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23775. */
  23776. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23777. var options = {
  23778. xmin: xmin,
  23779. zmin: zmin,
  23780. xmax: xmax,
  23781. zmax: zmax,
  23782. subdivisions: subdivisions,
  23783. precision: precision,
  23784. updatable: updatable
  23785. };
  23786. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23787. };
  23788. /**
  23789. * Creates a ground mesh from a height map.
  23790. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23791. * Please consider using the same method from the MeshBuilder class instead.
  23792. * The parameter `url` sets the URL of the height map image resource.
  23793. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23794. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23795. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23796. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23797. * 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).
  23798. * This function is passed the newly built mesh :
  23799. * ```javascript
  23800. * function(mesh) { // do things
  23801. * return; }
  23802. * ```
  23803. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23804. */
  23805. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23806. var options = {
  23807. width: width,
  23808. height: height,
  23809. subdivisions: subdivisions,
  23810. minHeight: minHeight,
  23811. maxHeight: maxHeight,
  23812. updatable: updatable,
  23813. onReady: onReady
  23814. };
  23815. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23816. };
  23817. /**
  23818. * Creates a tube mesh.
  23819. * 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.
  23820. * Please consider using the same method from the MeshBuilder class instead.
  23821. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23822. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23823. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23824. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23825. * 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.
  23826. * It must return a radius value (positive float) :
  23827. * ```javascript
  23828. * var radiusFunction = function(i, distance) {
  23829. * // do things
  23830. * return radius; }
  23831. * ```
  23832. * 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
  23833. * 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
  23834. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23835. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23836. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23837. */
  23838. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23839. var options = {
  23840. path: path,
  23841. radius: radius,
  23842. tessellation: tessellation,
  23843. radiusFunction: radiusFunction,
  23844. arc: 1,
  23845. cap: cap,
  23846. updatable: updatable,
  23847. sideOrientation: sideOrientation,
  23848. instance: instance
  23849. };
  23850. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23851. };
  23852. /**
  23853. * Creates a polyhedron mesh.
  23854. * Please consider using the same method from the MeshBuilder class instead.
  23855. * 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
  23856. * to choose the wanted type.
  23857. * The parameter `size` (positive float, default 1) sets the polygon size.
  23858. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23859. * 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`.
  23860. * 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
  23861. * 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)`).
  23862. * 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
  23863. * 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.
  23864. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23865. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23866. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23867. */
  23868. Mesh.CreatePolyhedron = function (name, options, scene) {
  23869. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23870. };
  23871. /**
  23872. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23873. * Please consider using the same method from the MeshBuilder class instead.
  23874. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23875. * 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`).
  23876. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23877. * 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.
  23878. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23879. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23880. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23881. */
  23882. Mesh.CreateIcoSphere = function (name, options, scene) {
  23883. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23884. };
  23885. /**
  23886. * Creates a decal mesh.
  23887. * Please consider using the same method from the MeshBuilder class instead.
  23888. * 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.
  23889. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23890. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23891. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23892. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23893. */
  23894. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23895. var options = {
  23896. position: position,
  23897. normal: normal,
  23898. size: size,
  23899. angle: angle
  23900. };
  23901. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23902. };
  23903. // Skeletons
  23904. /**
  23905. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23906. */
  23907. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23908. var source;
  23909. if (!this._sourcePositions) {
  23910. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23911. this._sourcePositions = new Float32Array(source);
  23912. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23913. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23914. }
  23915. }
  23916. return this._sourcePositions;
  23917. };
  23918. /**
  23919. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23920. */
  23921. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23922. var source;
  23923. if (!this._sourceNormals) {
  23924. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23925. this._sourceNormals = new Float32Array(source);
  23926. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23927. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23928. }
  23929. }
  23930. return this._sourceNormals;
  23931. };
  23932. /**
  23933. * Updates the vertex buffer by applying transformation from the bones.
  23934. * Returns the Mesh.
  23935. *
  23936. * @param {skeleton} skeleton to apply
  23937. */
  23938. Mesh.prototype.applySkeleton = function (skeleton) {
  23939. if (!this.geometry) {
  23940. return this;
  23941. }
  23942. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23943. return this;
  23944. }
  23945. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23946. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23947. return this;
  23948. }
  23949. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23950. return this;
  23951. }
  23952. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23953. return this;
  23954. }
  23955. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23956. return this;
  23957. }
  23958. if (!this._sourcePositions) {
  23959. var submeshes = this.subMeshes.slice();
  23960. this.setPositionsForCPUSkinning();
  23961. this.subMeshes = submeshes;
  23962. }
  23963. if (!this._sourceNormals) {
  23964. this.setNormalsForCPUSkinning();
  23965. }
  23966. // positionsData checks for not being Float32Array will only pass at most once
  23967. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23968. if (!(positionsData instanceof Float32Array)) {
  23969. positionsData = new Float32Array(positionsData);
  23970. }
  23971. // normalsData checks for not being Float32Array will only pass at most once
  23972. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23973. if (!(normalsData instanceof Float32Array)) {
  23974. normalsData = new Float32Array(normalsData);
  23975. }
  23976. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23977. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23978. var needExtras = this.numBoneInfluencers > 4;
  23979. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23980. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23981. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23982. var tempVector3 = BABYLON.Vector3.Zero();
  23983. var finalMatrix = new BABYLON.Matrix();
  23984. var tempMatrix = new BABYLON.Matrix();
  23985. var matWeightIdx = 0;
  23986. var inf;
  23987. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23988. var weight;
  23989. for (inf = 0; inf < 4; inf++) {
  23990. weight = matricesWeightsData[matWeightIdx + inf];
  23991. if (weight > 0) {
  23992. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23993. finalMatrix.addToSelf(tempMatrix);
  23994. }
  23995. else
  23996. break;
  23997. }
  23998. if (needExtras) {
  23999. for (inf = 0; inf < 4; inf++) {
  24000. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24001. if (weight > 0) {
  24002. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24003. finalMatrix.addToSelf(tempMatrix);
  24004. }
  24005. else
  24006. break;
  24007. }
  24008. }
  24009. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  24010. tempVector3.toArray(positionsData, index);
  24011. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  24012. tempVector3.toArray(normalsData, index);
  24013. finalMatrix.reset();
  24014. }
  24015. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  24016. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  24017. return this;
  24018. };
  24019. // Tools
  24020. /**
  24021. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  24022. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  24023. */
  24024. Mesh.MinMax = function (meshes) {
  24025. var minVector = null;
  24026. var maxVector = null;
  24027. meshes.forEach(function (mesh, index, array) {
  24028. var boundingBox = mesh.getBoundingInfo().boundingBox;
  24029. if (!minVector) {
  24030. minVector = boundingBox.minimumWorld;
  24031. maxVector = boundingBox.maximumWorld;
  24032. }
  24033. else {
  24034. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  24035. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  24036. }
  24037. });
  24038. return {
  24039. min: minVector,
  24040. max: maxVector
  24041. };
  24042. };
  24043. /**
  24044. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  24045. */
  24046. Mesh.Center = function (meshesOrMinMaxVector) {
  24047. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  24048. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  24049. };
  24050. /**
  24051. * Merge the array of meshes into a single mesh for performance reasons.
  24052. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  24053. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  24054. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  24055. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  24056. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  24057. */
  24058. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  24059. if (disposeSource === void 0) { disposeSource = true; }
  24060. var index;
  24061. if (!allow32BitsIndices) {
  24062. var totalVertices = 0;
  24063. // Counting vertices
  24064. for (index = 0; index < meshes.length; index++) {
  24065. if (meshes[index]) {
  24066. totalVertices += meshes[index].getTotalVertices();
  24067. if (totalVertices > 65536) {
  24068. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  24069. return null;
  24070. }
  24071. }
  24072. }
  24073. }
  24074. // Merge
  24075. var vertexData;
  24076. var otherVertexData;
  24077. var indiceArray = new Array();
  24078. var source;
  24079. for (index = 0; index < meshes.length; index++) {
  24080. if (meshes[index]) {
  24081. meshes[index].computeWorldMatrix(true);
  24082. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  24083. otherVertexData.transform(meshes[index].getWorldMatrix());
  24084. if (vertexData) {
  24085. vertexData.merge(otherVertexData);
  24086. }
  24087. else {
  24088. vertexData = otherVertexData;
  24089. source = meshes[index];
  24090. }
  24091. if (subdivideWithSubMeshes) {
  24092. indiceArray.push(meshes[index].getTotalIndices());
  24093. }
  24094. }
  24095. }
  24096. if (!meshSubclass) {
  24097. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  24098. }
  24099. vertexData.applyToMesh(meshSubclass);
  24100. // Setting properties
  24101. meshSubclass.material = source.material;
  24102. meshSubclass.checkCollisions = source.checkCollisions;
  24103. // Cleaning
  24104. if (disposeSource) {
  24105. for (index = 0; index < meshes.length; index++) {
  24106. if (meshes[index]) {
  24107. meshes[index].dispose();
  24108. }
  24109. }
  24110. }
  24111. // Subdivide
  24112. if (subdivideWithSubMeshes) {
  24113. //-- Suppresions du submesh global
  24114. meshSubclass.releaseSubMeshes();
  24115. index = 0;
  24116. var offset = 0;
  24117. //-- aplique la subdivision en fonction du tableau d'indices
  24118. while (index < indiceArray.length) {
  24119. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  24120. offset += indiceArray[index];
  24121. index++;
  24122. }
  24123. }
  24124. return meshSubclass;
  24125. };
  24126. return Mesh;
  24127. }(BABYLON.AbstractMesh));
  24128. // Consts
  24129. Mesh._FRONTSIDE = 0;
  24130. Mesh._BACKSIDE = 1;
  24131. Mesh._DOUBLESIDE = 2;
  24132. Mesh._DEFAULTSIDE = 0;
  24133. Mesh._NO_CAP = 0;
  24134. Mesh._CAP_START = 1;
  24135. Mesh._CAP_END = 2;
  24136. Mesh._CAP_ALL = 3;
  24137. BABYLON.Mesh = Mesh;
  24138. })(BABYLON || (BABYLON = {}));
  24139. //# sourceMappingURL=babylon.mesh.js.map
  24140. var BABYLON;
  24141. (function (BABYLON) {
  24142. var BaseSubMesh = (function () {
  24143. function BaseSubMesh() {
  24144. }
  24145. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  24146. get: function () {
  24147. return this._materialEffect;
  24148. },
  24149. enumerable: true,
  24150. configurable: true
  24151. });
  24152. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  24153. if (this._materialEffect === effect) {
  24154. if (!effect) {
  24155. this._materialDefines = undefined;
  24156. }
  24157. return;
  24158. }
  24159. this._materialDefines = defines;
  24160. this._materialEffect = effect;
  24161. };
  24162. return BaseSubMesh;
  24163. }());
  24164. BABYLON.BaseSubMesh = BaseSubMesh;
  24165. var SubMesh = (function (_super) {
  24166. __extends(SubMesh, _super);
  24167. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  24168. if (createBoundingBox === void 0) { createBoundingBox = true; }
  24169. var _this = _super.call(this) || this;
  24170. _this.materialIndex = materialIndex;
  24171. _this.verticesStart = verticesStart;
  24172. _this.verticesCount = verticesCount;
  24173. _this.indexStart = indexStart;
  24174. _this.indexCount = indexCount;
  24175. _this._renderId = 0;
  24176. _this._mesh = mesh;
  24177. _this._renderingMesh = renderingMesh || mesh;
  24178. mesh.subMeshes.push(_this);
  24179. _this._trianglePlanes = [];
  24180. _this._id = mesh.subMeshes.length - 1;
  24181. if (createBoundingBox) {
  24182. _this.refreshBoundingInfo();
  24183. mesh.computeWorldMatrix(true);
  24184. }
  24185. return _this;
  24186. }
  24187. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  24188. get: function () {
  24189. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  24190. },
  24191. enumerable: true,
  24192. configurable: true
  24193. });
  24194. /**
  24195. * Returns the submesh BoudingInfo object.
  24196. */
  24197. SubMesh.prototype.getBoundingInfo = function () {
  24198. if (this.IsGlobal) {
  24199. return this._mesh.getBoundingInfo();
  24200. }
  24201. return this._boundingInfo;
  24202. };
  24203. /**
  24204. * Sets the submesh BoundingInfo.
  24205. * Return the SubMesh.
  24206. */
  24207. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  24208. this._boundingInfo = boundingInfo;
  24209. return this;
  24210. };
  24211. /**
  24212. * Returns the mesh of the current submesh.
  24213. */
  24214. SubMesh.prototype.getMesh = function () {
  24215. return this._mesh;
  24216. };
  24217. /**
  24218. * Returns the rendering mesh of the submesh.
  24219. */
  24220. SubMesh.prototype.getRenderingMesh = function () {
  24221. return this._renderingMesh;
  24222. };
  24223. /**
  24224. * Returns the submesh material.
  24225. */
  24226. SubMesh.prototype.getMaterial = function () {
  24227. var rootMaterial = this._renderingMesh.material;
  24228. if (rootMaterial && rootMaterial.getSubMaterial) {
  24229. var multiMaterial = rootMaterial;
  24230. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  24231. if (this._currentMaterial !== effectiveMaterial) {
  24232. this._currentMaterial = effectiveMaterial;
  24233. this._materialDefines = undefined;
  24234. }
  24235. return effectiveMaterial;
  24236. }
  24237. if (!rootMaterial) {
  24238. return this._mesh.getScene().defaultMaterial;
  24239. }
  24240. return rootMaterial;
  24241. };
  24242. // Methods
  24243. /**
  24244. * Sets a new updated BoundingInfo object to the submesh.
  24245. * Returns the SubMesh.
  24246. */
  24247. SubMesh.prototype.refreshBoundingInfo = function () {
  24248. this._lastColliderWorldVertices = null;
  24249. if (this.IsGlobal) {
  24250. return;
  24251. }
  24252. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24253. if (!data) {
  24254. this._boundingInfo = this._mesh._boundingInfo;
  24255. return;
  24256. }
  24257. var indices = this._renderingMesh.getIndices();
  24258. var extend;
  24259. //is this the only submesh?
  24260. if (this.indexStart === 0 && this.indexCount === indices.length) {
  24261. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  24262. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  24263. }
  24264. else {
  24265. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  24266. }
  24267. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24268. return this;
  24269. };
  24270. SubMesh.prototype._checkCollision = function (collider) {
  24271. return this.getBoundingInfo()._checkCollision(collider);
  24272. };
  24273. /**
  24274. * Updates the submesh BoundingInfo.
  24275. * Returns the Submesh.
  24276. */
  24277. SubMesh.prototype.updateBoundingInfo = function (world) {
  24278. if (!this.getBoundingInfo()) {
  24279. this.refreshBoundingInfo();
  24280. }
  24281. this.getBoundingInfo().update(world);
  24282. return this;
  24283. };
  24284. /**
  24285. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  24286. * Boolean returned.
  24287. */
  24288. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  24289. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  24290. };
  24291. /**
  24292. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  24293. * Boolean returned.
  24294. */
  24295. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  24296. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  24297. };
  24298. /**
  24299. * Renders the submesh.
  24300. * Returns it.
  24301. */
  24302. SubMesh.prototype.render = function (enableAlphaMode) {
  24303. this._renderingMesh.render(this, enableAlphaMode);
  24304. return this;
  24305. };
  24306. /**
  24307. * Returns a new Index Buffer.
  24308. * Type returned : WebGLBuffer.
  24309. */
  24310. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  24311. if (!this._linesIndexBuffer) {
  24312. var linesIndices = [];
  24313. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24314. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  24315. }
  24316. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  24317. this.linesIndexCount = linesIndices.length;
  24318. }
  24319. return this._linesIndexBuffer;
  24320. };
  24321. /**
  24322. * True is the passed Ray intersects the submesh bounding box.
  24323. * Boolean returned.
  24324. */
  24325. SubMesh.prototype.canIntersects = function (ray) {
  24326. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  24327. };
  24328. /**
  24329. * Returns an object IntersectionInfo.
  24330. */
  24331. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  24332. var intersectInfo = null;
  24333. // LineMesh first as it's also a Mesh...
  24334. if (this._mesh instanceof BABYLON.LinesMesh) {
  24335. var lineMesh = this._mesh;
  24336. // Line test
  24337. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  24338. var p0 = positions[indices[index]];
  24339. var p1 = positions[indices[index + 1]];
  24340. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  24341. if (length < 0) {
  24342. continue;
  24343. }
  24344. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  24345. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  24346. if (fastCheck) {
  24347. break;
  24348. }
  24349. }
  24350. }
  24351. }
  24352. else {
  24353. // Triangles test
  24354. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24355. var p0 = positions[indices[index]];
  24356. var p1 = positions[indices[index + 1]];
  24357. var p2 = positions[indices[index + 2]];
  24358. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24359. if (currentIntersectInfo) {
  24360. if (currentIntersectInfo.distance < 0) {
  24361. continue;
  24362. }
  24363. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24364. intersectInfo = currentIntersectInfo;
  24365. intersectInfo.faceId = index / 3;
  24366. if (fastCheck) {
  24367. break;
  24368. }
  24369. }
  24370. }
  24371. }
  24372. }
  24373. return intersectInfo;
  24374. };
  24375. SubMesh.prototype._rebuild = function () {
  24376. if (this._linesIndexBuffer) {
  24377. this._linesIndexBuffer = null;
  24378. }
  24379. };
  24380. // Clone
  24381. /**
  24382. * Creates a new Submesh from the passed Mesh.
  24383. */
  24384. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24385. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24386. if (!this.IsGlobal) {
  24387. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24388. }
  24389. return result;
  24390. };
  24391. // Dispose
  24392. /**
  24393. * Disposes the Submesh.
  24394. * Returns nothing.
  24395. */
  24396. SubMesh.prototype.dispose = function () {
  24397. if (this._linesIndexBuffer) {
  24398. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24399. this._linesIndexBuffer = null;
  24400. }
  24401. // Remove from mesh
  24402. var index = this._mesh.subMeshes.indexOf(this);
  24403. this._mesh.subMeshes.splice(index, 1);
  24404. };
  24405. // Statics
  24406. /**
  24407. * Creates a new Submesh from the passed parameters :
  24408. * - materialIndex (integer) : the index of the main mesh material.
  24409. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24410. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24411. * - mesh (Mesh) : the main mesh to create the submesh from.
  24412. * - renderingMesh (optional Mesh) : rendering mesh.
  24413. */
  24414. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24415. var minVertexIndex = Number.MAX_VALUE;
  24416. var maxVertexIndex = -Number.MAX_VALUE;
  24417. renderingMesh = renderingMesh || mesh;
  24418. var indices = renderingMesh.getIndices();
  24419. for (var index = startIndex; index < startIndex + indexCount; index++) {
  24420. var vertexIndex = indices[index];
  24421. if (vertexIndex < minVertexIndex)
  24422. minVertexIndex = vertexIndex;
  24423. if (vertexIndex > maxVertexIndex)
  24424. maxVertexIndex = vertexIndex;
  24425. }
  24426. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  24427. };
  24428. return SubMesh;
  24429. }(BaseSubMesh));
  24430. BABYLON.SubMesh = SubMesh;
  24431. })(BABYLON || (BABYLON = {}));
  24432. //# sourceMappingURL=babylon.subMesh.js.map
  24433. var BABYLON;
  24434. (function (BABYLON) {
  24435. var EffectFallbacks = (function () {
  24436. function EffectFallbacks() {
  24437. this._defines = {};
  24438. this._currentRank = 32;
  24439. this._maxRank = -1;
  24440. }
  24441. EffectFallbacks.prototype.unBindMesh = function () {
  24442. this._mesh = null;
  24443. };
  24444. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24445. if (!this._defines[rank]) {
  24446. if (rank < this._currentRank) {
  24447. this._currentRank = rank;
  24448. }
  24449. if (rank > this._maxRank) {
  24450. this._maxRank = rank;
  24451. }
  24452. this._defines[rank] = new Array();
  24453. }
  24454. this._defines[rank].push(define);
  24455. };
  24456. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24457. this._meshRank = rank;
  24458. this._mesh = mesh;
  24459. if (rank < this._currentRank) {
  24460. this._currentRank = rank;
  24461. }
  24462. if (rank > this._maxRank) {
  24463. this._maxRank = rank;
  24464. }
  24465. };
  24466. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24467. get: function () {
  24468. return this._currentRank <= this._maxRank;
  24469. },
  24470. enumerable: true,
  24471. configurable: true
  24472. });
  24473. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24474. // First we try to switch to CPU skinning
  24475. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  24476. this._mesh.computeBonesUsingShaders = false;
  24477. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24478. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24479. var scene = this._mesh.getScene();
  24480. for (var index = 0; index < scene.meshes.length; index++) {
  24481. var otherMesh = scene.meshes[index];
  24482. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  24483. otherMesh.computeBonesUsingShaders = false;
  24484. }
  24485. }
  24486. }
  24487. else {
  24488. var currentFallbacks = this._defines[this._currentRank];
  24489. if (currentFallbacks) {
  24490. for (var index = 0; index < currentFallbacks.length; index++) {
  24491. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24492. }
  24493. }
  24494. this._currentRank++;
  24495. }
  24496. return currentDefines;
  24497. };
  24498. return EffectFallbacks;
  24499. }());
  24500. BABYLON.EffectFallbacks = EffectFallbacks;
  24501. var EffectCreationOptions = (function () {
  24502. function EffectCreationOptions() {
  24503. }
  24504. return EffectCreationOptions;
  24505. }());
  24506. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24507. var Effect = (function () {
  24508. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24509. var _this = this;
  24510. this.uniqueId = 0;
  24511. this.onCompileObservable = new BABYLON.Observable();
  24512. this.onErrorObservable = new BABYLON.Observable();
  24513. this.onBindObservable = new BABYLON.Observable();
  24514. this._uniformBuffersNames = {};
  24515. this._isReady = false;
  24516. this._compilationError = "";
  24517. this.name = baseName;
  24518. if (attributesNamesOrOptions.attributes) {
  24519. var options = attributesNamesOrOptions;
  24520. this._engine = uniformsNamesOrEngine;
  24521. this._attributesNames = options.attributes;
  24522. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24523. this._samplers = options.samplers;
  24524. this.defines = options.defines;
  24525. this.onError = options.onError;
  24526. this.onCompiled = options.onCompiled;
  24527. this._fallbacks = options.fallbacks;
  24528. this._indexParameters = options.indexParameters;
  24529. if (options.uniformBuffersNames) {
  24530. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24531. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24532. }
  24533. }
  24534. }
  24535. else {
  24536. this._engine = engine;
  24537. this.defines = defines;
  24538. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24539. this._samplers = samplers;
  24540. this._attributesNames = attributesNamesOrOptions;
  24541. this.onError = onError;
  24542. this.onCompiled = onCompiled;
  24543. this._indexParameters = indexParameters;
  24544. this._fallbacks = fallbacks;
  24545. }
  24546. this.uniqueId = Effect._uniqueIdSeed++;
  24547. var vertexSource;
  24548. var fragmentSource;
  24549. if (baseName.vertexElement) {
  24550. vertexSource = document.getElementById(baseName.vertexElement);
  24551. if (!vertexSource) {
  24552. vertexSource = baseName.vertexElement;
  24553. }
  24554. }
  24555. else {
  24556. vertexSource = baseName.vertex || baseName;
  24557. }
  24558. if (baseName.fragmentElement) {
  24559. fragmentSource = document.getElementById(baseName.fragmentElement);
  24560. if (!fragmentSource) {
  24561. fragmentSource = baseName.fragmentElement;
  24562. }
  24563. }
  24564. else {
  24565. fragmentSource = baseName.fragment || baseName;
  24566. }
  24567. this._loadVertexShader(vertexSource, function (vertexCode) {
  24568. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24569. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24570. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24571. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24572. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24573. if (baseName) {
  24574. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  24575. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  24576. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  24577. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  24578. }
  24579. else {
  24580. _this._vertexSourceCode = migratedVertexCode;
  24581. _this._fragmentSourceCode = migratedFragmentCode;
  24582. }
  24583. _this._prepareEffect();
  24584. });
  24585. });
  24586. });
  24587. });
  24588. });
  24589. });
  24590. }
  24591. Object.defineProperty(Effect.prototype, "key", {
  24592. get: function () {
  24593. return this._key;
  24594. },
  24595. enumerable: true,
  24596. configurable: true
  24597. });
  24598. // Properties
  24599. Effect.prototype.isReady = function () {
  24600. return this._isReady;
  24601. };
  24602. Effect.prototype.getEngine = function () {
  24603. return this._engine;
  24604. };
  24605. Effect.prototype.getProgram = function () {
  24606. return this._program;
  24607. };
  24608. Effect.prototype.getAttributesNames = function () {
  24609. return this._attributesNames;
  24610. };
  24611. Effect.prototype.getAttributeLocation = function (index) {
  24612. return this._attributes[index];
  24613. };
  24614. Effect.prototype.getAttributeLocationByName = function (name) {
  24615. var index = this._attributesNames.indexOf(name);
  24616. return this._attributes[index];
  24617. };
  24618. Effect.prototype.getAttributesCount = function () {
  24619. return this._attributes.length;
  24620. };
  24621. Effect.prototype.getUniformIndex = function (uniformName) {
  24622. return this._uniformsNames.indexOf(uniformName);
  24623. };
  24624. Effect.prototype.getUniform = function (uniformName) {
  24625. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24626. };
  24627. Effect.prototype.getSamplers = function () {
  24628. return this._samplers;
  24629. };
  24630. Effect.prototype.getCompilationError = function () {
  24631. return this._compilationError;
  24632. };
  24633. // Methods
  24634. Effect.prototype.executeWhenCompiled = function (func) {
  24635. if (this.isReady()) {
  24636. func(this);
  24637. return;
  24638. }
  24639. this.onCompileObservable.add(function (effect) {
  24640. func(effect);
  24641. });
  24642. };
  24643. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24644. // DOM element ?
  24645. if (vertex instanceof HTMLElement) {
  24646. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24647. callback(vertexCode);
  24648. return;
  24649. }
  24650. // Base64 encoded ?
  24651. if (vertex.substr(0, 7) === "base64:") {
  24652. var vertexBinary = window.atob(vertex.substr(7));
  24653. callback(vertexBinary);
  24654. return;
  24655. }
  24656. // Is in local store ?
  24657. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24658. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24659. return;
  24660. }
  24661. var vertexShaderUrl;
  24662. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24663. vertexShaderUrl = vertex;
  24664. }
  24665. else {
  24666. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24667. }
  24668. // Vertex shader
  24669. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24670. };
  24671. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24672. // DOM element ?
  24673. if (fragment instanceof HTMLElement) {
  24674. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24675. callback(fragmentCode);
  24676. return;
  24677. }
  24678. // Base64 encoded ?
  24679. if (fragment.substr(0, 7) === "base64:") {
  24680. var fragmentBinary = window.atob(fragment.substr(7));
  24681. callback(fragmentBinary);
  24682. return;
  24683. }
  24684. // Is in local store ?
  24685. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24686. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24687. return;
  24688. }
  24689. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24690. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24691. return;
  24692. }
  24693. var fragmentShaderUrl;
  24694. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24695. fragmentShaderUrl = fragment;
  24696. }
  24697. else {
  24698. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24699. }
  24700. // Fragment shader
  24701. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24702. };
  24703. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24704. // Rebuild shaders source code
  24705. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24706. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24707. vertexCode = prefix + vertexCode;
  24708. fragmentCode = prefix + fragmentCode;
  24709. // Number lines of shaders source code
  24710. var i = 2;
  24711. var regex = /\n/gm;
  24712. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24713. i = 2;
  24714. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24715. // Dump shaders name and formatted source code
  24716. if (this.name.vertexElement) {
  24717. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24718. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24719. }
  24720. else if (this.name.vertex) {
  24721. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24722. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24723. }
  24724. else {
  24725. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24726. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24727. }
  24728. };
  24729. ;
  24730. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24731. var preparedSourceCode = this._processPrecision(sourceCode);
  24732. if (this._engine.webGLVersion == 1) {
  24733. callback(preparedSourceCode);
  24734. return;
  24735. }
  24736. // Already converted
  24737. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24738. callback(preparedSourceCode.replace("#version 300 es", ""));
  24739. return;
  24740. }
  24741. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  24742. // Remove extensions
  24743. // #extension GL_OES_standard_derivatives : enable
  24744. // #extension GL_EXT_shader_texture_lod : enable
  24745. // #extension GL_EXT_frag_depth : enable
  24746. // #extension GL_EXT_draw_buffers : require
  24747. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  24748. var result = preparedSourceCode.replace(regex, "");
  24749. // Migrate to GLSL v300
  24750. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24751. result = result.replace(/attribute[ \t]/g, "in ");
  24752. result = result.replace(/[ \t]attribute/g, " in");
  24753. if (isFragment) {
  24754. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  24755. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  24756. result = result.replace(/texture2D\s*\(/g, "texture(");
  24757. result = result.replace(/textureCube\s*\(/g, "texture(");
  24758. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24759. result = result.replace(/gl_FragColor/g, "glFragColor");
  24760. result = result.replace(/gl_FragData/g, "glFragData");
  24761. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  24762. }
  24763. callback(result);
  24764. };
  24765. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24766. var _this = this;
  24767. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24768. var match = regex.exec(sourceCode);
  24769. var returnValue = new String(sourceCode);
  24770. while (match != null) {
  24771. var includeFile = match[1];
  24772. // Uniform declaration
  24773. if (includeFile.indexOf("__decl__") !== -1) {
  24774. includeFile = includeFile.replace(/__decl__/, "");
  24775. if (this._engine.supportsUniformBuffers) {
  24776. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24777. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24778. }
  24779. includeFile = includeFile + "Declaration";
  24780. }
  24781. if (Effect.IncludesShadersStore[includeFile]) {
  24782. // Substitution
  24783. var includeContent = Effect.IncludesShadersStore[includeFile];
  24784. if (match[2]) {
  24785. var splits = match[3].split(",");
  24786. for (var index = 0; index < splits.length; index += 2) {
  24787. var source = new RegExp(splits[index], "g");
  24788. var dest = splits[index + 1];
  24789. includeContent = includeContent.replace(source, dest);
  24790. }
  24791. }
  24792. if (match[4]) {
  24793. var indexString = match[5];
  24794. if (indexString.indexOf("..") !== -1) {
  24795. var indexSplits = indexString.split("..");
  24796. var minIndex = parseInt(indexSplits[0]);
  24797. var maxIndex = parseInt(indexSplits[1]);
  24798. var sourceIncludeContent = includeContent.slice(0);
  24799. includeContent = "";
  24800. if (isNaN(maxIndex)) {
  24801. maxIndex = this._indexParameters[indexSplits[1]];
  24802. }
  24803. for (var i = minIndex; i < maxIndex; i++) {
  24804. if (!this._engine.supportsUniformBuffers) {
  24805. // Ubo replacement
  24806. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24807. return p1 + "{X}";
  24808. });
  24809. }
  24810. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24811. }
  24812. }
  24813. else {
  24814. if (!this._engine.supportsUniformBuffers) {
  24815. // Ubo replacement
  24816. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24817. return p1 + "{X}";
  24818. });
  24819. }
  24820. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24821. }
  24822. }
  24823. // Replace
  24824. returnValue = returnValue.replace(match[0], includeContent);
  24825. }
  24826. else {
  24827. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24828. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24829. Effect.IncludesShadersStore[includeFile] = fileContent;
  24830. _this._processIncludes(returnValue, callback);
  24831. });
  24832. return;
  24833. }
  24834. match = regex.exec(sourceCode);
  24835. }
  24836. callback(returnValue);
  24837. };
  24838. Effect.prototype._processPrecision = function (source) {
  24839. if (source.indexOf("precision highp float") === -1) {
  24840. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24841. source = "precision mediump float;\n" + source;
  24842. }
  24843. else {
  24844. source = "precision highp float;\n" + source;
  24845. }
  24846. }
  24847. else {
  24848. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24849. source = source.replace("precision highp float", "precision mediump float");
  24850. }
  24851. }
  24852. return source;
  24853. };
  24854. Effect.prototype._prepareEffect = function () {
  24855. var attributesNames = this._attributesNames;
  24856. var defines = this.defines;
  24857. var fallbacks = this._fallbacks;
  24858. this._valueCache = {};
  24859. try {
  24860. var engine = this._engine;
  24861. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24862. if (engine.webGLVersion > 1) {
  24863. for (var name in this._uniformBuffersNames) {
  24864. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24865. }
  24866. }
  24867. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24868. this._attributes = engine.getAttributes(this._program, attributesNames);
  24869. var index;
  24870. for (index = 0; index < this._samplers.length; index++) {
  24871. var sampler = this.getUniform(this._samplers[index]);
  24872. if (sampler == null) {
  24873. this._samplers.splice(index, 1);
  24874. index--;
  24875. }
  24876. }
  24877. engine.bindSamplers(this);
  24878. this._compilationError = "";
  24879. this._isReady = true;
  24880. if (this.onCompiled) {
  24881. this.onCompiled(this);
  24882. }
  24883. this.onCompileObservable.notifyObservers(this);
  24884. this.onCompileObservable.clear();
  24885. // Unbind mesh reference in fallbacks
  24886. if (this._fallbacks) {
  24887. this._fallbacks.unBindMesh();
  24888. }
  24889. }
  24890. catch (e) {
  24891. this._compilationError = e.message;
  24892. // Let's go through fallbacks then
  24893. BABYLON.Tools.Error("Unable to compile effect:");
  24894. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24895. return " " + uniform;
  24896. }));
  24897. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24898. return " " + attribute;
  24899. }));
  24900. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24901. BABYLON.Tools.Error("Error: " + this._compilationError);
  24902. if (fallbacks && fallbacks.isMoreFallbacks) {
  24903. BABYLON.Tools.Error("Trying next fallback.");
  24904. this.defines = fallbacks.reduce(this.defines);
  24905. this._prepareEffect();
  24906. }
  24907. else {
  24908. if (this.onError) {
  24909. this.onError(this, this._compilationError);
  24910. }
  24911. this.onErrorObservable.notifyObservers(this);
  24912. this.onErrorObservable.clear();
  24913. // Unbind mesh reference in fallbacks
  24914. if (this._fallbacks) {
  24915. this._fallbacks.unBindMesh();
  24916. }
  24917. }
  24918. }
  24919. };
  24920. Object.defineProperty(Effect.prototype, "isSupported", {
  24921. get: function () {
  24922. return this._compilationError === "";
  24923. },
  24924. enumerable: true,
  24925. configurable: true
  24926. });
  24927. Effect.prototype._bindTexture = function (channel, texture) {
  24928. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24929. };
  24930. Effect.prototype.setTexture = function (channel, texture) {
  24931. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24932. };
  24933. Effect.prototype.setTextureArray = function (channel, textures) {
  24934. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24935. var initialPos = this._samplers.indexOf(channel);
  24936. for (var index = 1; index < textures.length; index++) {
  24937. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24938. }
  24939. }
  24940. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24941. };
  24942. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24943. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24944. };
  24945. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24946. var cache = this._valueCache[uniformName];
  24947. var flag = matrix.updateFlag;
  24948. if (cache !== undefined && cache === flag) {
  24949. return false;
  24950. }
  24951. this._valueCache[uniformName] = flag;
  24952. return true;
  24953. };
  24954. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24955. var cache = this._valueCache[uniformName];
  24956. if (!cache) {
  24957. cache = [x, y];
  24958. this._valueCache[uniformName] = cache;
  24959. return true;
  24960. }
  24961. var changed = false;
  24962. if (cache[0] !== x) {
  24963. cache[0] = x;
  24964. changed = true;
  24965. }
  24966. if (cache[1] !== y) {
  24967. cache[1] = y;
  24968. changed = true;
  24969. }
  24970. return changed;
  24971. };
  24972. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24973. var cache = this._valueCache[uniformName];
  24974. if (!cache) {
  24975. cache = [x, y, z];
  24976. this._valueCache[uniformName] = cache;
  24977. return true;
  24978. }
  24979. var changed = false;
  24980. if (cache[0] !== x) {
  24981. cache[0] = x;
  24982. changed = true;
  24983. }
  24984. if (cache[1] !== y) {
  24985. cache[1] = y;
  24986. changed = true;
  24987. }
  24988. if (cache[2] !== z) {
  24989. cache[2] = z;
  24990. changed = true;
  24991. }
  24992. return changed;
  24993. };
  24994. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24995. var cache = this._valueCache[uniformName];
  24996. if (!cache) {
  24997. cache = [x, y, z, w];
  24998. this._valueCache[uniformName] = cache;
  24999. return true;
  25000. }
  25001. var changed = false;
  25002. if (cache[0] !== x) {
  25003. cache[0] = x;
  25004. changed = true;
  25005. }
  25006. if (cache[1] !== y) {
  25007. cache[1] = y;
  25008. changed = true;
  25009. }
  25010. if (cache[2] !== z) {
  25011. cache[2] = z;
  25012. changed = true;
  25013. }
  25014. if (cache[3] !== w) {
  25015. cache[3] = w;
  25016. changed = true;
  25017. }
  25018. return changed;
  25019. };
  25020. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  25021. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  25022. return;
  25023. }
  25024. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  25025. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  25026. };
  25027. Effect.prototype.bindUniformBlock = function (blockName, index) {
  25028. this._engine.bindUniformBlock(this._program, blockName, index);
  25029. };
  25030. Effect.prototype.setIntArray = function (uniformName, array) {
  25031. this._valueCache[uniformName] = null;
  25032. this._engine.setIntArray(this.getUniform(uniformName), array);
  25033. return this;
  25034. };
  25035. Effect.prototype.setIntArray2 = function (uniformName, array) {
  25036. this._valueCache[uniformName] = null;
  25037. this._engine.setIntArray2(this.getUniform(uniformName), array);
  25038. return this;
  25039. };
  25040. Effect.prototype.setIntArray3 = function (uniformName, array) {
  25041. this._valueCache[uniformName] = null;
  25042. this._engine.setIntArray3(this.getUniform(uniformName), array);
  25043. return this;
  25044. };
  25045. Effect.prototype.setIntArray4 = function (uniformName, array) {
  25046. this._valueCache[uniformName] = null;
  25047. this._engine.setIntArray4(this.getUniform(uniformName), array);
  25048. return this;
  25049. };
  25050. Effect.prototype.setFloatArray = function (uniformName, array) {
  25051. this._valueCache[uniformName] = null;
  25052. this._engine.setFloatArray(this.getUniform(uniformName), array);
  25053. return this;
  25054. };
  25055. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  25056. this._valueCache[uniformName] = null;
  25057. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  25058. return this;
  25059. };
  25060. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  25061. this._valueCache[uniformName] = null;
  25062. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  25063. return this;
  25064. };
  25065. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  25066. this._valueCache[uniformName] = null;
  25067. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  25068. return this;
  25069. };
  25070. Effect.prototype.setArray = function (uniformName, array) {
  25071. this._valueCache[uniformName] = null;
  25072. this._engine.setArray(this.getUniform(uniformName), array);
  25073. return this;
  25074. };
  25075. Effect.prototype.setArray2 = function (uniformName, array) {
  25076. this._valueCache[uniformName] = null;
  25077. this._engine.setArray2(this.getUniform(uniformName), array);
  25078. return this;
  25079. };
  25080. Effect.prototype.setArray3 = function (uniformName, array) {
  25081. this._valueCache[uniformName] = null;
  25082. this._engine.setArray3(this.getUniform(uniformName), array);
  25083. return this;
  25084. };
  25085. Effect.prototype.setArray4 = function (uniformName, array) {
  25086. this._valueCache[uniformName] = null;
  25087. this._engine.setArray4(this.getUniform(uniformName), array);
  25088. return this;
  25089. };
  25090. Effect.prototype.setMatrices = function (uniformName, matrices) {
  25091. if (!matrices) {
  25092. return;
  25093. }
  25094. this._valueCache[uniformName] = null;
  25095. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  25096. return this;
  25097. };
  25098. Effect.prototype.setMatrix = function (uniformName, matrix) {
  25099. if (this._cacheMatrix(uniformName, matrix)) {
  25100. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  25101. }
  25102. return this;
  25103. };
  25104. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  25105. this._valueCache[uniformName] = null;
  25106. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  25107. return this;
  25108. };
  25109. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25110. this._valueCache[uniformName] = null;
  25111. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25112. return this;
  25113. };
  25114. Effect.prototype.setFloat = function (uniformName, value) {
  25115. var cache = this._valueCache[uniformName];
  25116. if (cache !== undefined && cache === value)
  25117. return this;
  25118. this._valueCache[uniformName] = value;
  25119. this._engine.setFloat(this.getUniform(uniformName), value);
  25120. return this;
  25121. };
  25122. Effect.prototype.setBool = function (uniformName, bool) {
  25123. var cache = this._valueCache[uniformName];
  25124. if (cache !== undefined && cache === bool)
  25125. return this;
  25126. this._valueCache[uniformName] = bool;
  25127. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25128. return this;
  25129. };
  25130. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25131. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25132. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25133. }
  25134. return this;
  25135. };
  25136. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25137. if (this._cacheFloat2(uniformName, x, y)) {
  25138. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25139. }
  25140. return this;
  25141. };
  25142. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25143. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25144. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25145. }
  25146. return this;
  25147. };
  25148. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25149. if (this._cacheFloat3(uniformName, x, y, z)) {
  25150. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25151. }
  25152. return this;
  25153. };
  25154. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25155. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25156. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25157. }
  25158. return this;
  25159. };
  25160. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25161. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25162. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25163. }
  25164. return this;
  25165. };
  25166. Effect.prototype.setColor3 = function (uniformName, color3) {
  25167. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25168. this._engine.setColor3(this.getUniform(uniformName), color3);
  25169. }
  25170. return this;
  25171. };
  25172. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25173. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25174. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25175. }
  25176. return this;
  25177. };
  25178. Effect.ResetCache = function () {
  25179. Effect._baseCache = {};
  25180. };
  25181. return Effect;
  25182. }());
  25183. Effect._uniqueIdSeed = 0;
  25184. Effect._baseCache = {};
  25185. // Statics
  25186. Effect.ShadersStore = {};
  25187. Effect.IncludesShadersStore = {};
  25188. BABYLON.Effect = Effect;
  25189. })(BABYLON || (BABYLON = {}));
  25190. //# sourceMappingURL=babylon.effect.js.map
  25191. var BABYLON;
  25192. (function (BABYLON) {
  25193. var MaterialHelper = (function () {
  25194. function MaterialHelper() {
  25195. }
  25196. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  25197. defines._needUVs = true;
  25198. defines[key] = true;
  25199. if (texture.getTextureMatrix().isIdentity(true)) {
  25200. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  25201. if (texture.coordinatesIndex === 0) {
  25202. defines["MAINUV1"] = true;
  25203. }
  25204. else {
  25205. defines["MAINUV2"] = true;
  25206. }
  25207. }
  25208. else {
  25209. defines[key + "DIRECTUV"] = 0;
  25210. }
  25211. };
  25212. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  25213. var matrix = texture.getTextureMatrix();
  25214. if (!matrix.isIdentity(true)) {
  25215. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  25216. }
  25217. };
  25218. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  25219. if (defines._areMiscDirty) {
  25220. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  25221. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  25222. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  25223. }
  25224. };
  25225. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  25226. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  25227. var changed = false;
  25228. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  25229. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  25230. changed = true;
  25231. }
  25232. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  25233. defines["ALPHATEST"] = !defines["ALPHATEST"];
  25234. changed = true;
  25235. }
  25236. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  25237. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  25238. changed = true;
  25239. }
  25240. if (defines["INSTANCES"] !== useInstances) {
  25241. defines["INSTANCES"] = useInstances;
  25242. changed = true;
  25243. }
  25244. if (changed) {
  25245. defines.markAsUnprocessed();
  25246. }
  25247. };
  25248. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  25249. if (useMorphTargets === void 0) { useMorphTargets = false; }
  25250. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  25251. return false;
  25252. }
  25253. defines._normals = defines._needNormals;
  25254. defines._uvs = defines._needUVs;
  25255. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  25256. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25257. defines["TANGENT"] = true;
  25258. }
  25259. if (defines._needUVs) {
  25260. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  25261. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  25262. }
  25263. else {
  25264. defines["UV1"] = false;
  25265. defines["UV2"] = false;
  25266. }
  25267. if (useVertexColor) {
  25268. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  25269. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  25270. }
  25271. if (useBones) {
  25272. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25273. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  25274. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  25275. }
  25276. else {
  25277. defines["NUM_BONE_INFLUENCERS"] = 0;
  25278. defines["BonesPerMesh"] = 0;
  25279. }
  25280. }
  25281. if (useMorphTargets) {
  25282. if (mesh.morphTargetManager) {
  25283. var manager = mesh.morphTargetManager;
  25284. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  25285. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  25286. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  25287. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  25288. }
  25289. else {
  25290. defines["MORPHTARGETS_TANGENT"] = false;
  25291. defines["MORPHTARGETS_NORMAL"] = false;
  25292. defines["MORPHTARGETS"] = false;
  25293. defines["NUM_MORPH_INFLUENCERS"] = 0;
  25294. }
  25295. }
  25296. return true;
  25297. };
  25298. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  25299. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25300. if (disableLighting === void 0) { disableLighting = false; }
  25301. if (!defines._areLightsDirty) {
  25302. return defines._needNormals;
  25303. }
  25304. var lightIndex = 0;
  25305. var needNormals = false;
  25306. var needRebuild = false;
  25307. var lightmapMode = false;
  25308. var shadowEnabled = false;
  25309. var specularEnabled = false;
  25310. if (scene.lightsEnabled && !disableLighting) {
  25311. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25312. var light = _a[_i];
  25313. needNormals = true;
  25314. if (defines["LIGHT" + lightIndex] === undefined) {
  25315. needRebuild = true;
  25316. }
  25317. defines["LIGHT" + lightIndex] = true;
  25318. defines["SPOTLIGHT" + lightIndex] = false;
  25319. defines["HEMILIGHT" + lightIndex] = false;
  25320. defines["POINTLIGHT" + lightIndex] = false;
  25321. defines["DIRLIGHT" + lightIndex] = false;
  25322. var type;
  25323. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  25324. type = "SPOTLIGHT" + lightIndex;
  25325. }
  25326. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  25327. type = "HEMILIGHT" + lightIndex;
  25328. }
  25329. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  25330. type = "POINTLIGHT" + lightIndex;
  25331. }
  25332. else {
  25333. type = "DIRLIGHT" + lightIndex;
  25334. }
  25335. defines[type] = true;
  25336. // Specular
  25337. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  25338. specularEnabled = true;
  25339. }
  25340. // Shadows
  25341. defines["SHADOW" + lightIndex] = false;
  25342. defines["SHADOWPCF" + lightIndex] = false;
  25343. defines["SHADOWESM" + lightIndex] = false;
  25344. defines["SHADOWCUBE" + lightIndex] = false;
  25345. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  25346. var shadowGenerator = light.getShadowGenerator();
  25347. if (shadowGenerator) {
  25348. shadowEnabled = true;
  25349. shadowGenerator.prepareDefines(defines, lightIndex);
  25350. }
  25351. }
  25352. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25353. lightmapMode = true;
  25354. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25355. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  25356. }
  25357. else {
  25358. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  25359. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  25360. }
  25361. lightIndex++;
  25362. if (lightIndex === maxSimultaneousLights)
  25363. break;
  25364. }
  25365. }
  25366. defines["SPECULARTERM"] = specularEnabled;
  25367. defines["SHADOWS"] = shadowEnabled;
  25368. // Resetting all other lights if any
  25369. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  25370. if (defines["LIGHT" + index] !== undefined) {
  25371. defines["LIGHT" + index] = false;
  25372. defines["HEMILIGHT" + lightIndex] = false;
  25373. defines["POINTLIGHT" + lightIndex] = false;
  25374. defines["DIRLIGHT" + lightIndex] = false;
  25375. defines["SPOTLIGHT" + lightIndex] = false;
  25376. defines["SHADOW" + lightIndex] = false;
  25377. }
  25378. }
  25379. var caps = scene.getEngine().getCaps();
  25380. if (defines["SHADOWFLOAT"] === undefined) {
  25381. needRebuild = true;
  25382. }
  25383. defines["SHADOWFLOAT"] = shadowEnabled &&
  25384. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  25385. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  25386. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  25387. if (needRebuild) {
  25388. defines.rebuild();
  25389. }
  25390. return needNormals;
  25391. };
  25392. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  25393. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25394. var uniformsList, uniformBuffersList, samplersList, defines;
  25395. if (uniformsListOrOptions.uniformsNames) {
  25396. var options = uniformsListOrOptions;
  25397. uniformsList = options.uniformsNames;
  25398. uniformBuffersList = options.uniformBuffersNames;
  25399. samplersList = options.samplers;
  25400. defines = options.defines;
  25401. maxSimultaneousLights = options.maxSimultaneousLights;
  25402. }
  25403. else {
  25404. uniformsList = uniformsListOrOptions;
  25405. }
  25406. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25407. if (!defines["LIGHT" + lightIndex]) {
  25408. break;
  25409. }
  25410. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  25411. if (uniformBuffersList) {
  25412. uniformBuffersList.push("Light" + lightIndex);
  25413. }
  25414. samplersList.push("shadowSampler" + lightIndex);
  25415. }
  25416. if (defines["NUM_MORPH_INFLUENCERS"]) {
  25417. uniformsList.push("morphTargetInfluences");
  25418. }
  25419. };
  25420. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25421. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25422. if (!defines["SHADOWS"]) {
  25423. return;
  25424. }
  25425. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25426. if (!defines["LIGHT" + lightIndex]) {
  25427. break;
  25428. }
  25429. if (lightIndex > 0) {
  25430. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25431. }
  25432. if (defines["SHADOW" + lightIndex]) {
  25433. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25434. }
  25435. if (defines["SHADOWPCF" + lightIndex]) {
  25436. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25437. }
  25438. if (defines["SHADOWESM" + lightIndex]) {
  25439. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  25440. }
  25441. }
  25442. };
  25443. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  25444. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  25445. if (influencers > 0) {
  25446. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  25447. var manager = mesh.morphTargetManager;
  25448. var normal = manager.supportsNormals && defines["NORMAL"];
  25449. var tangent = manager.supportsTangents && defines["TANGENT"];
  25450. for (var index = 0; index < influencers; index++) {
  25451. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  25452. if (normal) {
  25453. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  25454. }
  25455. if (tangent) {
  25456. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  25457. }
  25458. if (attribs.length > maxAttributesCount) {
  25459. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  25460. }
  25461. }
  25462. }
  25463. };
  25464. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25465. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25466. fallbacks.addCPUSkinningFallback(0, mesh);
  25467. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25468. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25469. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25470. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25471. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25472. }
  25473. }
  25474. };
  25475. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25476. if (defines["INSTANCES"]) {
  25477. attribs.push("world0");
  25478. attribs.push("world1");
  25479. attribs.push("world2");
  25480. attribs.push("world3");
  25481. }
  25482. };
  25483. // Bindings
  25484. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  25485. if (light.shadowEnabled && mesh.receiveShadows) {
  25486. var shadowGenerator = light.getShadowGenerator();
  25487. if (shadowGenerator) {
  25488. shadowGenerator.bindShadowLight(lightIndex, effect);
  25489. }
  25490. }
  25491. };
  25492. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25493. light.transferToEffect(effect, lightIndex + "");
  25494. };
  25495. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25496. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25497. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25498. var lightIndex = 0;
  25499. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25500. var light = _a[_i];
  25501. var scaledIntensity = light.getScaledIntensity();
  25502. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25503. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25504. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25505. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25506. if (defines["SPECULARTERM"]) {
  25507. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25508. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25509. }
  25510. // Shadows
  25511. if (scene.shadowsEnabled) {
  25512. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25513. }
  25514. light._uniformBuffer.update();
  25515. lightIndex++;
  25516. if (lightIndex === maxSimultaneousLights)
  25517. break;
  25518. }
  25519. };
  25520. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25521. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25522. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25523. effect.setColor3("vFogColor", scene.fogColor);
  25524. }
  25525. };
  25526. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25527. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25528. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25529. if (matrices) {
  25530. effect.setMatrices("mBones", matrices);
  25531. }
  25532. }
  25533. };
  25534. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25535. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25536. return;
  25537. }
  25538. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25539. };
  25540. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25541. if (defines["LOGARITHMICDEPTH"]) {
  25542. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25543. }
  25544. };
  25545. MaterialHelper.BindClipPlane = function (effect, scene) {
  25546. if (scene.clipPlane) {
  25547. var clipPlane = scene.clipPlane;
  25548. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25549. }
  25550. };
  25551. return MaterialHelper;
  25552. }());
  25553. BABYLON.MaterialHelper = MaterialHelper;
  25554. })(BABYLON || (BABYLON = {}));
  25555. //# sourceMappingURL=babylon.materialHelper.js.map
  25556. var BABYLON;
  25557. (function (BABYLON) {
  25558. var MaterialDefines = (function () {
  25559. function MaterialDefines() {
  25560. this._isDirty = true;
  25561. this._areLightsDirty = true;
  25562. this._areAttributesDirty = true;
  25563. this._areTexturesDirty = true;
  25564. this._areFresnelDirty = true;
  25565. this._areMiscDirty = true;
  25566. this._areImageProcessingDirty = true;
  25567. this._normals = false;
  25568. this._uvs = false;
  25569. this._needNormals = false;
  25570. this._needUVs = false;
  25571. }
  25572. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25573. get: function () {
  25574. return this._isDirty;
  25575. },
  25576. enumerable: true,
  25577. configurable: true
  25578. });
  25579. MaterialDefines.prototype.markAsProcessed = function () {
  25580. this._isDirty = false;
  25581. this._areAttributesDirty = false;
  25582. this._areTexturesDirty = false;
  25583. this._areFresnelDirty = false;
  25584. this._areLightsDirty = false;
  25585. this._areMiscDirty = false;
  25586. this._areImageProcessingDirty = false;
  25587. };
  25588. MaterialDefines.prototype.markAsUnprocessed = function () {
  25589. this._isDirty = true;
  25590. };
  25591. MaterialDefines.prototype.markAllAsDirty = function () {
  25592. this._areTexturesDirty = true;
  25593. this._areAttributesDirty = true;
  25594. this._areLightsDirty = true;
  25595. this._areFresnelDirty = true;
  25596. this._areMiscDirty = true;
  25597. this._areImageProcessingDirty = true;
  25598. this._isDirty = true;
  25599. };
  25600. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25601. this._areImageProcessingDirty = true;
  25602. this._isDirty = true;
  25603. };
  25604. MaterialDefines.prototype.markAsLightDirty = function () {
  25605. this._areLightsDirty = true;
  25606. this._isDirty = true;
  25607. };
  25608. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25609. this._areAttributesDirty = true;
  25610. this._isDirty = true;
  25611. };
  25612. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25613. this._areTexturesDirty = true;
  25614. this._isDirty = true;
  25615. };
  25616. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25617. this._areFresnelDirty = true;
  25618. this._isDirty = true;
  25619. };
  25620. MaterialDefines.prototype.markAsMiscDirty = function () {
  25621. this._areMiscDirty = true;
  25622. this._isDirty = true;
  25623. };
  25624. MaterialDefines.prototype.rebuild = function () {
  25625. if (this._keys) {
  25626. delete this._keys;
  25627. }
  25628. this._keys = [];
  25629. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25630. var key = _a[_i];
  25631. if (key[0] === "_") {
  25632. continue;
  25633. }
  25634. this._keys.push(key);
  25635. }
  25636. };
  25637. MaterialDefines.prototype.isEqual = function (other) {
  25638. if (this._keys.length !== other._keys.length) {
  25639. return false;
  25640. }
  25641. for (var index = 0; index < this._keys.length; index++) {
  25642. var prop = this._keys[index];
  25643. if (this[prop] !== other[prop]) {
  25644. return false;
  25645. }
  25646. }
  25647. return true;
  25648. };
  25649. MaterialDefines.prototype.cloneTo = function (other) {
  25650. if (this._keys.length !== other._keys.length) {
  25651. other._keys = this._keys.slice(0);
  25652. }
  25653. for (var index = 0; index < this._keys.length; index++) {
  25654. var prop = this._keys[index];
  25655. other[prop] = this[prop];
  25656. }
  25657. };
  25658. MaterialDefines.prototype.reset = function () {
  25659. for (var index = 0; index < this._keys.length; index++) {
  25660. var prop = this._keys[index];
  25661. if (typeof (this[prop]) === "number") {
  25662. this[prop] = 0;
  25663. }
  25664. else {
  25665. this[prop] = false;
  25666. }
  25667. }
  25668. };
  25669. MaterialDefines.prototype.toString = function () {
  25670. var result = "";
  25671. for (var index = 0; index < this._keys.length; index++) {
  25672. var prop = this._keys[index];
  25673. var value = this[prop];
  25674. if (typeof (value) === "number") {
  25675. result += "#define " + prop + " " + this[prop] + "\n";
  25676. }
  25677. else if (value) {
  25678. result += "#define " + prop + "\n";
  25679. }
  25680. }
  25681. return result;
  25682. };
  25683. return MaterialDefines;
  25684. }());
  25685. BABYLON.MaterialDefines = MaterialDefines;
  25686. var Material = (function () {
  25687. function Material(name, scene, doNotAdd) {
  25688. this.checkReadyOnEveryCall = false;
  25689. this.checkReadyOnlyOnce = false;
  25690. this.state = "";
  25691. this.alpha = 1.0;
  25692. this._backFaceCulling = true;
  25693. this.doNotSerialize = false;
  25694. this.storeEffectOnSubMeshes = false;
  25695. /**
  25696. * An event triggered when the material is disposed.
  25697. * @type {BABYLON.Observable}
  25698. */
  25699. this.onDisposeObservable = new BABYLON.Observable();
  25700. /**
  25701. * An event triggered when the material is bound.
  25702. * @type {BABYLON.Observable}
  25703. */
  25704. this.onBindObservable = new BABYLON.Observable();
  25705. /**
  25706. * An event triggered when the material is unbound.
  25707. * @type {BABYLON.Observable}
  25708. */
  25709. this.onUnBindObservable = new BABYLON.Observable();
  25710. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25711. this._needDepthPrePass = false;
  25712. this.disableDepthWrite = false;
  25713. this.forceDepthWrite = false;
  25714. this.separateCullingPass = false;
  25715. this._fogEnabled = true;
  25716. this.pointSize = 1.0;
  25717. this.zOffset = 0;
  25718. this._wasPreviouslyReady = false;
  25719. this._fillMode = Material.TriangleFillMode;
  25720. this.name = name;
  25721. this.id = name || BABYLON.Tools.RandomId();
  25722. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25723. if (this._scene.useRightHandedSystem) {
  25724. this.sideOrientation = Material.ClockWiseSideOrientation;
  25725. }
  25726. else {
  25727. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25728. }
  25729. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25730. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  25731. if (!doNotAdd) {
  25732. this._scene.materials.push(this);
  25733. }
  25734. }
  25735. Object.defineProperty(Material, "TriangleFillMode", {
  25736. get: function () {
  25737. return Material._TriangleFillMode;
  25738. },
  25739. enumerable: true,
  25740. configurable: true
  25741. });
  25742. Object.defineProperty(Material, "WireFrameFillMode", {
  25743. get: function () {
  25744. return Material._WireFrameFillMode;
  25745. },
  25746. enumerable: true,
  25747. configurable: true
  25748. });
  25749. Object.defineProperty(Material, "PointFillMode", {
  25750. get: function () {
  25751. return Material._PointFillMode;
  25752. },
  25753. enumerable: true,
  25754. configurable: true
  25755. });
  25756. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25757. get: function () {
  25758. return Material._ClockWiseSideOrientation;
  25759. },
  25760. enumerable: true,
  25761. configurable: true
  25762. });
  25763. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25764. get: function () {
  25765. return Material._CounterClockWiseSideOrientation;
  25766. },
  25767. enumerable: true,
  25768. configurable: true
  25769. });
  25770. Object.defineProperty(Material, "TextureDirtyFlag", {
  25771. get: function () {
  25772. return Material._TextureDirtyFlag;
  25773. },
  25774. enumerable: true,
  25775. configurable: true
  25776. });
  25777. Object.defineProperty(Material, "LightDirtyFlag", {
  25778. get: function () {
  25779. return Material._LightDirtyFlag;
  25780. },
  25781. enumerable: true,
  25782. configurable: true
  25783. });
  25784. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25785. get: function () {
  25786. return Material._FresnelDirtyFlag;
  25787. },
  25788. enumerable: true,
  25789. configurable: true
  25790. });
  25791. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25792. get: function () {
  25793. return Material._AttributesDirtyFlag;
  25794. },
  25795. enumerable: true,
  25796. configurable: true
  25797. });
  25798. Object.defineProperty(Material, "MiscDirtyFlag", {
  25799. get: function () {
  25800. return Material._MiscDirtyFlag;
  25801. },
  25802. enumerable: true,
  25803. configurable: true
  25804. });
  25805. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25806. get: function () {
  25807. return this._backFaceCulling;
  25808. },
  25809. set: function (value) {
  25810. if (this._backFaceCulling === value) {
  25811. return;
  25812. }
  25813. this._backFaceCulling = value;
  25814. this.markAsDirty(Material.TextureDirtyFlag);
  25815. },
  25816. enumerable: true,
  25817. configurable: true
  25818. });
  25819. Object.defineProperty(Material.prototype, "onDispose", {
  25820. set: function (callback) {
  25821. if (this._onDisposeObserver) {
  25822. this.onDisposeObservable.remove(this._onDisposeObserver);
  25823. }
  25824. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25825. },
  25826. enumerable: true,
  25827. configurable: true
  25828. });
  25829. Object.defineProperty(Material.prototype, "onBind", {
  25830. set: function (callback) {
  25831. if (this._onBindObserver) {
  25832. this.onBindObservable.remove(this._onBindObserver);
  25833. }
  25834. this._onBindObserver = this.onBindObservable.add(callback);
  25835. },
  25836. enumerable: true,
  25837. configurable: true
  25838. });
  25839. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  25840. get: function () {
  25841. return this._needDepthPrePass;
  25842. },
  25843. set: function (value) {
  25844. if (this._needDepthPrePass === value) {
  25845. return;
  25846. }
  25847. this._needDepthPrePass = value;
  25848. if (this._needDepthPrePass) {
  25849. this.checkReadyOnEveryCall = true;
  25850. }
  25851. },
  25852. enumerable: true,
  25853. configurable: true
  25854. });
  25855. Object.defineProperty(Material.prototype, "fogEnabled", {
  25856. get: function () {
  25857. return this._fogEnabled;
  25858. },
  25859. set: function (value) {
  25860. if (this._fogEnabled === value) {
  25861. return;
  25862. }
  25863. this._fogEnabled = value;
  25864. this.markAsDirty(Material.MiscDirtyFlag);
  25865. },
  25866. enumerable: true,
  25867. configurable: true
  25868. });
  25869. Object.defineProperty(Material.prototype, "wireframe", {
  25870. get: function () {
  25871. return this._fillMode === Material.WireFrameFillMode;
  25872. },
  25873. set: function (value) {
  25874. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25875. },
  25876. enumerable: true,
  25877. configurable: true
  25878. });
  25879. Object.defineProperty(Material.prototype, "pointsCloud", {
  25880. get: function () {
  25881. return this._fillMode === Material.PointFillMode;
  25882. },
  25883. set: function (value) {
  25884. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25885. },
  25886. enumerable: true,
  25887. configurable: true
  25888. });
  25889. Object.defineProperty(Material.prototype, "fillMode", {
  25890. get: function () {
  25891. return this._fillMode;
  25892. },
  25893. set: function (value) {
  25894. if (this._fillMode === value) {
  25895. return;
  25896. }
  25897. this._fillMode = value;
  25898. this.markAsDirty(Material.MiscDirtyFlag);
  25899. },
  25900. enumerable: true,
  25901. configurable: true
  25902. });
  25903. /**
  25904. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25905. * subclasses should override adding information pertainent to themselves
  25906. */
  25907. Material.prototype.toString = function (fullDetails) {
  25908. var ret = "Name: " + this.name;
  25909. if (fullDetails) {
  25910. }
  25911. return ret;
  25912. };
  25913. /**
  25914. * Child classes can use it to update shaders
  25915. */
  25916. Material.prototype.getClassName = function () {
  25917. return "Material";
  25918. };
  25919. Object.defineProperty(Material.prototype, "isFrozen", {
  25920. get: function () {
  25921. return this.checkReadyOnlyOnce;
  25922. },
  25923. enumerable: true,
  25924. configurable: true
  25925. });
  25926. Material.prototype.freeze = function () {
  25927. this.checkReadyOnlyOnce = true;
  25928. };
  25929. Material.prototype.unfreeze = function () {
  25930. this.checkReadyOnlyOnce = false;
  25931. };
  25932. Material.prototype.isReady = function (mesh, useInstances) {
  25933. return true;
  25934. };
  25935. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25936. return false;
  25937. };
  25938. Material.prototype.getEffect = function () {
  25939. return this._effect;
  25940. };
  25941. Material.prototype.getScene = function () {
  25942. return this._scene;
  25943. };
  25944. Material.prototype.needAlphaBlending = function () {
  25945. return (this.alpha < 1.0);
  25946. };
  25947. Material.prototype.needAlphaTesting = function () {
  25948. return false;
  25949. };
  25950. Material.prototype.getAlphaTestTexture = function () {
  25951. return null;
  25952. };
  25953. Material.prototype.markDirty = function () {
  25954. this._wasPreviouslyReady = false;
  25955. };
  25956. Material.prototype._preBind = function (effect, overrideOrientation) {
  25957. var engine = this._scene.getEngine();
  25958. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  25959. var reverse = orientation === Material.ClockWiseSideOrientation;
  25960. engine.enableEffect(effect ? effect : this._effect);
  25961. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25962. return reverse;
  25963. };
  25964. Material.prototype.bind = function (world, mesh) {
  25965. };
  25966. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25967. };
  25968. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25969. };
  25970. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25971. sceneUbo.bindToEffect(effect, "Scene");
  25972. };
  25973. Material.prototype.bindView = function (effect) {
  25974. if (!this._useUBO) {
  25975. effect.setMatrix("view", this.getScene().getViewMatrix());
  25976. }
  25977. else {
  25978. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25979. }
  25980. };
  25981. Material.prototype.bindViewProjection = function (effect) {
  25982. if (!this._useUBO) {
  25983. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25984. }
  25985. else {
  25986. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25987. }
  25988. };
  25989. Material.prototype._afterBind = function (mesh) {
  25990. this._scene._cachedMaterial = this;
  25991. if (mesh) {
  25992. this._scene._cachedVisibility = mesh.visibility;
  25993. }
  25994. else {
  25995. this._scene._cachedVisibility = 1;
  25996. }
  25997. this.onBindObservable.notifyObservers(mesh);
  25998. if (this.disableDepthWrite) {
  25999. var engine = this._scene.getEngine();
  26000. this._cachedDepthWriteState = engine.getDepthWrite();
  26001. engine.setDepthWrite(false);
  26002. }
  26003. };
  26004. Material.prototype.unbind = function () {
  26005. this.onUnBindObservable.notifyObservers(this);
  26006. if (this.disableDepthWrite) {
  26007. var engine = this._scene.getEngine();
  26008. engine.setDepthWrite(this._cachedDepthWriteState);
  26009. }
  26010. };
  26011. Material.prototype.getActiveTextures = function () {
  26012. return [];
  26013. };
  26014. Material.prototype.hasTexture = function (texture) {
  26015. return false;
  26016. };
  26017. Material.prototype.clone = function (name) {
  26018. return null;
  26019. };
  26020. Material.prototype.getBindedMeshes = function () {
  26021. var result = new Array();
  26022. for (var index = 0; index < this._scene.meshes.length; index++) {
  26023. var mesh = this._scene.meshes[index];
  26024. if (mesh.material === this) {
  26025. result.push(mesh);
  26026. }
  26027. }
  26028. return result;
  26029. };
  26030. /**
  26031. * Force shader compilation including textures ready check
  26032. */
  26033. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  26034. var _this = this;
  26035. var subMesh = new BABYLON.BaseSubMesh();
  26036. var scene = this.getScene();
  26037. var engine = scene.getEngine();
  26038. var checkReady = function () {
  26039. if (!_this._scene || !_this._scene.getEngine()) {
  26040. return;
  26041. }
  26042. if (subMesh._materialDefines) {
  26043. subMesh._materialDefines._renderId = -1;
  26044. }
  26045. var alphaTestState = engine.getAlphaTesting();
  26046. var clipPlaneState = scene.clipPlane;
  26047. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  26048. if (options && options.clipPlane) {
  26049. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  26050. }
  26051. if (_this.storeEffectOnSubMeshes) {
  26052. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  26053. if (onCompiled) {
  26054. onCompiled(_this);
  26055. }
  26056. }
  26057. else {
  26058. setTimeout(checkReady, 16);
  26059. }
  26060. }
  26061. else {
  26062. if (_this.isReady(mesh)) {
  26063. if (onCompiled) {
  26064. onCompiled(_this);
  26065. }
  26066. }
  26067. else {
  26068. setTimeout(checkReady, 16);
  26069. }
  26070. }
  26071. engine.setAlphaTesting(alphaTestState);
  26072. if (options && options.clipPlane) {
  26073. scene.clipPlane = clipPlaneState;
  26074. }
  26075. };
  26076. checkReady();
  26077. };
  26078. Material.prototype.markAsDirty = function (flag) {
  26079. if (flag & Material.TextureDirtyFlag) {
  26080. this._markAllSubMeshesAsTexturesDirty();
  26081. }
  26082. if (flag & Material.LightDirtyFlag) {
  26083. this._markAllSubMeshesAsLightsDirty();
  26084. }
  26085. if (flag & Material.FresnelDirtyFlag) {
  26086. this._markAllSubMeshesAsFresnelDirty();
  26087. }
  26088. if (flag & Material.AttributesDirtyFlag) {
  26089. this._markAllSubMeshesAsAttributesDirty();
  26090. }
  26091. if (flag & Material.MiscDirtyFlag) {
  26092. this._markAllSubMeshesAsMiscDirty();
  26093. }
  26094. this.getScene().resetCachedMaterial();
  26095. };
  26096. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  26097. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  26098. var mesh = _a[_i];
  26099. if (!mesh.subMeshes) {
  26100. continue;
  26101. }
  26102. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26103. var subMesh = _c[_b];
  26104. if (subMesh.getMaterial() !== this) {
  26105. continue;
  26106. }
  26107. if (!subMesh._materialDefines) {
  26108. continue;
  26109. }
  26110. func(subMesh._materialDefines);
  26111. }
  26112. }
  26113. };
  26114. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  26115. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  26116. };
  26117. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  26118. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  26119. };
  26120. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  26121. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  26122. };
  26123. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  26124. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  26125. };
  26126. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  26127. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  26128. };
  26129. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  26130. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  26131. };
  26132. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26133. // Animations
  26134. this.getScene().stopAnimation(this);
  26135. // Remove from scene
  26136. var index = this._scene.materials.indexOf(this);
  26137. if (index >= 0) {
  26138. this._scene.materials.splice(index, 1);
  26139. }
  26140. // Remove from meshes
  26141. for (index = 0; index < this._scene.meshes.length; index++) {
  26142. var mesh = this._scene.meshes[index];
  26143. if (mesh.material === this) {
  26144. mesh.material = null;
  26145. if (mesh.geometry) {
  26146. var geometry = mesh.geometry;
  26147. if (this.storeEffectOnSubMeshes) {
  26148. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  26149. var subMesh = _a[_i];
  26150. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  26151. }
  26152. }
  26153. else {
  26154. geometry._releaseVertexArrayObject(this._effect);
  26155. }
  26156. }
  26157. }
  26158. }
  26159. this._uniformBuffer.dispose();
  26160. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26161. if (forceDisposeEffect && this._effect) {
  26162. if (this.storeEffectOnSubMeshes) {
  26163. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26164. var subMesh = _c[_b];
  26165. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  26166. }
  26167. }
  26168. else {
  26169. this._scene.getEngine()._releaseEffect(this._effect);
  26170. }
  26171. this._effect = null;
  26172. }
  26173. // Callback
  26174. this.onDisposeObservable.notifyObservers(this);
  26175. this.onDisposeObservable.clear();
  26176. this.onBindObservable.clear();
  26177. this.onUnBindObservable.clear();
  26178. };
  26179. Material.prototype.serialize = function () {
  26180. return BABYLON.SerializationHelper.Serialize(this);
  26181. };
  26182. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26183. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26184. multiMaterial.id = parsedMultiMaterial.id;
  26185. if (BABYLON.Tags) {
  26186. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26187. }
  26188. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26189. var subMatId = parsedMultiMaterial.materials[matIndex];
  26190. if (subMatId) {
  26191. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26192. }
  26193. else {
  26194. multiMaterial.subMaterials.push(null);
  26195. }
  26196. }
  26197. return multiMaterial;
  26198. };
  26199. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26200. if (!parsedMaterial.customType) {
  26201. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26202. }
  26203. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  26204. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  26205. if (!BABYLON.LegacyPBRMaterial) {
  26206. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  26207. return;
  26208. }
  26209. }
  26210. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26211. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26212. ;
  26213. };
  26214. return Material;
  26215. }());
  26216. Material._TriangleFillMode = 0;
  26217. Material._WireFrameFillMode = 1;
  26218. Material._PointFillMode = 2;
  26219. Material._ClockWiseSideOrientation = 0;
  26220. Material._CounterClockWiseSideOrientation = 1;
  26221. Material._TextureDirtyFlag = 1;
  26222. Material._LightDirtyFlag = 2;
  26223. Material._FresnelDirtyFlag = 4;
  26224. Material._AttributesDirtyFlag = 8;
  26225. Material._MiscDirtyFlag = 16;
  26226. __decorate([
  26227. BABYLON.serialize()
  26228. ], Material.prototype, "id", void 0);
  26229. __decorate([
  26230. BABYLON.serialize()
  26231. ], Material.prototype, "name", void 0);
  26232. __decorate([
  26233. BABYLON.serialize()
  26234. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26235. __decorate([
  26236. BABYLON.serialize()
  26237. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26238. __decorate([
  26239. BABYLON.serialize()
  26240. ], Material.prototype, "state", void 0);
  26241. __decorate([
  26242. BABYLON.serialize()
  26243. ], Material.prototype, "alpha", void 0);
  26244. __decorate([
  26245. BABYLON.serialize("backFaceCulling")
  26246. ], Material.prototype, "_backFaceCulling", void 0);
  26247. __decorate([
  26248. BABYLON.serialize()
  26249. ], Material.prototype, "sideOrientation", void 0);
  26250. __decorate([
  26251. BABYLON.serialize()
  26252. ], Material.prototype, "alphaMode", void 0);
  26253. __decorate([
  26254. BABYLON.serialize()
  26255. ], Material.prototype, "_needDepthPrePass", void 0);
  26256. __decorate([
  26257. BABYLON.serialize()
  26258. ], Material.prototype, "disableDepthWrite", void 0);
  26259. __decorate([
  26260. BABYLON.serialize()
  26261. ], Material.prototype, "forceDepthWrite", void 0);
  26262. __decorate([
  26263. BABYLON.serialize()
  26264. ], Material.prototype, "separateCullingPass", void 0);
  26265. __decorate([
  26266. BABYLON.serialize("fogEnabled")
  26267. ], Material.prototype, "_fogEnabled", void 0);
  26268. __decorate([
  26269. BABYLON.serialize()
  26270. ], Material.prototype, "pointSize", void 0);
  26271. __decorate([
  26272. BABYLON.serialize()
  26273. ], Material.prototype, "zOffset", void 0);
  26274. __decorate([
  26275. BABYLON.serialize()
  26276. ], Material.prototype, "wireframe", null);
  26277. __decorate([
  26278. BABYLON.serialize()
  26279. ], Material.prototype, "pointsCloud", null);
  26280. __decorate([
  26281. BABYLON.serialize()
  26282. ], Material.prototype, "fillMode", null);
  26283. BABYLON.Material = Material;
  26284. })(BABYLON || (BABYLON = {}));
  26285. //# sourceMappingURL=babylon.material.js.map
  26286. var BABYLON;
  26287. (function (BABYLON) {
  26288. var UniformBuffer = (function () {
  26289. /**
  26290. * Uniform buffer objects.
  26291. *
  26292. * Handles blocks of uniform on the GPU.
  26293. *
  26294. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  26295. *
  26296. * For more information, please refer to :
  26297. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  26298. */
  26299. function UniformBuffer(engine, data, dynamic) {
  26300. this._engine = engine;
  26301. this._noUBO = !engine.supportsUniformBuffers;
  26302. this._dynamic = dynamic;
  26303. this._data = data || [];
  26304. this._uniformLocations = {};
  26305. this._uniformSizes = {};
  26306. this._uniformLocationPointer = 0;
  26307. this._needSync = false;
  26308. if (this._noUBO) {
  26309. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  26310. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  26311. this.updateFloat = this._updateFloatForEffect;
  26312. this.updateFloat2 = this._updateFloat2ForEffect;
  26313. this.updateFloat3 = this._updateFloat3ForEffect;
  26314. this.updateFloat4 = this._updateFloat4ForEffect;
  26315. this.updateMatrix = this._updateMatrixForEffect;
  26316. this.updateVector3 = this._updateVector3ForEffect;
  26317. this.updateVector4 = this._updateVector4ForEffect;
  26318. this.updateColor3 = this._updateColor3ForEffect;
  26319. this.updateColor4 = this._updateColor4ForEffect;
  26320. }
  26321. else {
  26322. this._engine._uniformBuffers.push(this);
  26323. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  26324. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  26325. this.updateFloat = this._updateFloatForUniform;
  26326. this.updateFloat2 = this._updateFloat2ForUniform;
  26327. this.updateFloat3 = this._updateFloat3ForUniform;
  26328. this.updateFloat4 = this._updateFloat4ForUniform;
  26329. this.updateMatrix = this._updateMatrixForUniform;
  26330. this.updateVector3 = this._updateVector3ForUniform;
  26331. this.updateVector4 = this._updateVector4ForUniform;
  26332. this.updateColor3 = this._updateColor3ForUniform;
  26333. this.updateColor4 = this._updateColor4ForUniform;
  26334. }
  26335. }
  26336. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  26337. // Properties
  26338. /**
  26339. * Indicates if the buffer is using the WebGL2 UBO implementation,
  26340. * or just falling back on setUniformXXX calls.
  26341. */
  26342. get: function () {
  26343. return !this._noUBO;
  26344. },
  26345. enumerable: true,
  26346. configurable: true
  26347. });
  26348. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  26349. /**
  26350. * Indicates if the WebGL underlying uniform buffer is in sync
  26351. * with the javascript cache data.
  26352. */
  26353. get: function () {
  26354. return !this._needSync;
  26355. },
  26356. enumerable: true,
  26357. configurable: true
  26358. });
  26359. /**
  26360. * Indicates if the WebGL underlying uniform buffer is dynamic.
  26361. * Also, a dynamic UniformBuffer will disable cache verification and always
  26362. * update the underlying WebGL uniform buffer to the GPU.
  26363. */
  26364. UniformBuffer.prototype.isDynamic = function () {
  26365. return this._dynamic;
  26366. };
  26367. /**
  26368. * The data cache on JS side.
  26369. */
  26370. UniformBuffer.prototype.getData = function () {
  26371. return this._bufferData;
  26372. };
  26373. /**
  26374. * The underlying WebGL Uniform buffer.
  26375. */
  26376. UniformBuffer.prototype.getBuffer = function () {
  26377. return this._buffer;
  26378. };
  26379. /**
  26380. * std140 layout specifies how to align data within an UBO structure.
  26381. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  26382. * for specs.
  26383. */
  26384. UniformBuffer.prototype._fillAlignment = function (size) {
  26385. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  26386. // and 4x4 matrices
  26387. // TODO : change if other types are used
  26388. var alignment;
  26389. if (size <= 2) {
  26390. alignment = size;
  26391. }
  26392. else {
  26393. alignment = 4;
  26394. }
  26395. if ((this._uniformLocationPointer % alignment) !== 0) {
  26396. var oldPointer = this._uniformLocationPointer;
  26397. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  26398. var diff = this._uniformLocationPointer - oldPointer;
  26399. for (var i = 0; i < diff; i++) {
  26400. this._data.push(0);
  26401. }
  26402. }
  26403. };
  26404. /**
  26405. * Adds an uniform in the buffer.
  26406. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  26407. * for the layout to be correct !
  26408. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26409. * @param {number|number[]} size Data size, or data directly.
  26410. */
  26411. UniformBuffer.prototype.addUniform = function (name, size) {
  26412. if (this._noUBO) {
  26413. return;
  26414. }
  26415. if (this._uniformLocations[name] !== undefined) {
  26416. // Already existing uniform
  26417. return;
  26418. }
  26419. // This function must be called in the order of the shader layout !
  26420. // size can be the size of the uniform, or data directly
  26421. var data;
  26422. if (size instanceof Array) {
  26423. data = size;
  26424. size = data.length;
  26425. }
  26426. else {
  26427. size = size;
  26428. data = [];
  26429. // Fill with zeros
  26430. for (var i = 0; i < size; i++) {
  26431. data.push(0);
  26432. }
  26433. }
  26434. this._fillAlignment(size);
  26435. this._uniformSizes[name] = size;
  26436. this._uniformLocations[name] = this._uniformLocationPointer;
  26437. this._uniformLocationPointer += size;
  26438. for (var i = 0; i < size; i++) {
  26439. this._data.push(data[i]);
  26440. }
  26441. this._needSync = true;
  26442. };
  26443. /**
  26444. * Wrapper for addUniform.
  26445. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26446. * @param {Matrix} mat A 4x4 matrix.
  26447. */
  26448. UniformBuffer.prototype.addMatrix = function (name, mat) {
  26449. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  26450. };
  26451. /**
  26452. * Wrapper for addUniform.
  26453. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26454. * @param {number} x
  26455. * @param {number} y
  26456. */
  26457. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  26458. var temp = [x, y];
  26459. this.addUniform(name, temp);
  26460. };
  26461. /**
  26462. * Wrapper for addUniform.
  26463. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26464. * @param {number} x
  26465. * @param {number} y
  26466. * @param {number} z
  26467. */
  26468. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  26469. var temp = [x, y, z];
  26470. this.addUniform(name, temp);
  26471. };
  26472. /**
  26473. * Wrapper for addUniform.
  26474. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26475. * @param {Color3} color
  26476. */
  26477. UniformBuffer.prototype.addColor3 = function (name, color) {
  26478. var temp = [];
  26479. color.toArray(temp);
  26480. this.addUniform(name, temp);
  26481. };
  26482. /**
  26483. * Wrapper for addUniform.
  26484. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26485. * @param {Color3} color
  26486. * @param {number} alpha
  26487. */
  26488. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  26489. var temp = [];
  26490. color.toArray(temp);
  26491. temp.push(alpha);
  26492. this.addUniform(name, temp);
  26493. };
  26494. /**
  26495. * Wrapper for addUniform.
  26496. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26497. * @param {Vector3} vector
  26498. */
  26499. UniformBuffer.prototype.addVector3 = function (name, vector) {
  26500. var temp = [];
  26501. vector.toArray(temp);
  26502. this.addUniform(name, temp);
  26503. };
  26504. /**
  26505. * Wrapper for addUniform.
  26506. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26507. */
  26508. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  26509. this.addUniform(name, 12);
  26510. };
  26511. /**
  26512. * Wrapper for addUniform.
  26513. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26514. */
  26515. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  26516. this.addUniform(name, 8);
  26517. };
  26518. /**
  26519. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  26520. */
  26521. UniformBuffer.prototype.create = function () {
  26522. if (this._noUBO) {
  26523. return;
  26524. }
  26525. if (this._buffer) {
  26526. return; // nothing to do
  26527. }
  26528. // See spec, alignment must be filled as a vec4
  26529. this._fillAlignment(4);
  26530. this._bufferData = new Float32Array(this._data);
  26531. this._rebuild();
  26532. this._needSync = true;
  26533. };
  26534. UniformBuffer.prototype._rebuild = function () {
  26535. if (this._noUBO) {
  26536. return;
  26537. }
  26538. if (this._dynamic) {
  26539. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26540. }
  26541. else {
  26542. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26543. }
  26544. };
  26545. /**
  26546. * Updates the WebGL Uniform Buffer on the GPU.
  26547. * If the `dynamic` flag is set to true, no cache comparison is done.
  26548. * Otherwise, the buffer will be updated only if the cache differs.
  26549. */
  26550. UniformBuffer.prototype.update = function () {
  26551. if (!this._buffer) {
  26552. this.create();
  26553. return;
  26554. }
  26555. if (!this._dynamic && !this._needSync) {
  26556. return;
  26557. }
  26558. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26559. this._needSync = false;
  26560. };
  26561. /**
  26562. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26563. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26564. * @param {number[]|Float32Array} data Flattened data
  26565. * @param {number} size Size of the data.
  26566. */
  26567. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26568. var location = this._uniformLocations[uniformName];
  26569. if (location === undefined) {
  26570. if (this._buffer) {
  26571. // Cannot add an uniform if the buffer is already created
  26572. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26573. return;
  26574. }
  26575. this.addUniform(uniformName, size);
  26576. location = this._uniformLocations[uniformName];
  26577. }
  26578. if (!this._buffer) {
  26579. this.create();
  26580. }
  26581. if (!this._dynamic) {
  26582. // Cache for static uniform buffers
  26583. var changed = false;
  26584. for (var i = 0; i < size; i++) {
  26585. if (this._bufferData[location + i] !== data[i]) {
  26586. changed = true;
  26587. this._bufferData[location + i] = data[i];
  26588. }
  26589. }
  26590. this._needSync = this._needSync || changed;
  26591. }
  26592. else {
  26593. // No cache for dynamic
  26594. for (var i = 0; i < size; i++) {
  26595. this._bufferData[location + i] = data[i];
  26596. }
  26597. }
  26598. };
  26599. // Update methods
  26600. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26601. // To match std140, matrix must be realigned
  26602. for (var i = 0; i < 3; i++) {
  26603. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26604. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26605. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26606. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26607. }
  26608. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26609. };
  26610. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26611. this._currentEffect.setMatrix3x3(name, matrix);
  26612. };
  26613. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26614. this._currentEffect.setMatrix2x2(name, matrix);
  26615. };
  26616. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26617. // To match std140, matrix must be realigned
  26618. for (var i = 0; i < 2; i++) {
  26619. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26620. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26621. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26622. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26623. }
  26624. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26625. };
  26626. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26627. this._currentEffect.setFloat(name, x);
  26628. };
  26629. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26630. UniformBuffer._tempBuffer[0] = x;
  26631. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26632. };
  26633. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26634. if (suffix === void 0) { suffix = ""; }
  26635. this._currentEffect.setFloat2(name + suffix, x, y);
  26636. };
  26637. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26638. if (suffix === void 0) { suffix = ""; }
  26639. UniformBuffer._tempBuffer[0] = x;
  26640. UniformBuffer._tempBuffer[1] = y;
  26641. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26642. };
  26643. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26644. if (suffix === void 0) { suffix = ""; }
  26645. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26646. };
  26647. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26648. if (suffix === void 0) { suffix = ""; }
  26649. UniformBuffer._tempBuffer[0] = x;
  26650. UniformBuffer._tempBuffer[1] = y;
  26651. UniformBuffer._tempBuffer[2] = z;
  26652. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26653. };
  26654. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26655. if (suffix === void 0) { suffix = ""; }
  26656. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26657. };
  26658. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26659. if (suffix === void 0) { suffix = ""; }
  26660. UniformBuffer._tempBuffer[0] = x;
  26661. UniformBuffer._tempBuffer[1] = y;
  26662. UniformBuffer._tempBuffer[2] = z;
  26663. UniformBuffer._tempBuffer[3] = w;
  26664. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26665. };
  26666. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26667. this._currentEffect.setMatrix(name, mat);
  26668. };
  26669. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26670. this.updateUniform(name, mat.toArray(), 16);
  26671. };
  26672. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26673. this._currentEffect.setVector3(name, vector);
  26674. };
  26675. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26676. vector.toArray(UniformBuffer._tempBuffer);
  26677. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26678. };
  26679. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26680. this._currentEffect.setVector4(name, vector);
  26681. };
  26682. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26683. vector.toArray(UniformBuffer._tempBuffer);
  26684. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26685. };
  26686. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26687. if (suffix === void 0) { suffix = ""; }
  26688. this._currentEffect.setColor3(name + suffix, color);
  26689. };
  26690. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26691. if (suffix === void 0) { suffix = ""; }
  26692. color.toArray(UniformBuffer._tempBuffer);
  26693. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26694. };
  26695. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26696. if (suffix === void 0) { suffix = ""; }
  26697. this._currentEffect.setColor4(name + suffix, color, alpha);
  26698. };
  26699. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26700. if (suffix === void 0) { suffix = ""; }
  26701. color.toArray(UniformBuffer._tempBuffer);
  26702. UniformBuffer._tempBuffer[3] = alpha;
  26703. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26704. };
  26705. /**
  26706. * Sets a sampler uniform on the effect.
  26707. * @param {string} name Name of the sampler.
  26708. * @param {Texture} texture
  26709. */
  26710. UniformBuffer.prototype.setTexture = function (name, texture) {
  26711. this._currentEffect.setTexture(name, texture);
  26712. };
  26713. /**
  26714. * Directly updates the value of the uniform in the cache AND on the GPU.
  26715. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26716. * @param {number[]|Float32Array} data Flattened data
  26717. */
  26718. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26719. this.updateUniform(uniformName, data, data.length);
  26720. this.update();
  26721. };
  26722. /**
  26723. * Binds this uniform buffer to an effect.
  26724. * @param {Effect} effect
  26725. * @param {string} name Name of the uniform block in the shader.
  26726. */
  26727. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26728. this._currentEffect = effect;
  26729. if (this._noUBO) {
  26730. return;
  26731. }
  26732. effect.bindUniformBuffer(this._buffer, name);
  26733. };
  26734. /**
  26735. * Disposes the uniform buffer.
  26736. */
  26737. UniformBuffer.prototype.dispose = function () {
  26738. if (this._noUBO) {
  26739. return;
  26740. }
  26741. var index = this._engine._uniformBuffers.indexOf(this);
  26742. if (index !== -1) {
  26743. this._engine._uniformBuffers.splice(index, 1);
  26744. }
  26745. if (!this._buffer) {
  26746. return;
  26747. }
  26748. if (this._engine._releaseBuffer(this._buffer)) {
  26749. this._buffer = null;
  26750. }
  26751. };
  26752. return UniformBuffer;
  26753. }());
  26754. // Pool for avoiding memory leaks
  26755. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26756. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26757. BABYLON.UniformBuffer = UniformBuffer;
  26758. })(BABYLON || (BABYLON = {}));
  26759. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26760. var BABYLON;
  26761. (function (BABYLON) {
  26762. var PushMaterial = (function (_super) {
  26763. __extends(PushMaterial, _super);
  26764. function PushMaterial(name, scene) {
  26765. var _this = _super.call(this, name, scene) || this;
  26766. _this.storeEffectOnSubMeshes = true;
  26767. return _this;
  26768. }
  26769. PushMaterial.prototype.getEffect = function () {
  26770. return this._activeEffect;
  26771. };
  26772. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26773. if (!mesh) {
  26774. return false;
  26775. }
  26776. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26777. return true;
  26778. }
  26779. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26780. };
  26781. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26782. this._activeEffect.setMatrix("world", world);
  26783. };
  26784. PushMaterial.prototype.bind = function (world, mesh) {
  26785. if (!mesh) {
  26786. return;
  26787. }
  26788. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26789. };
  26790. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26791. _super.prototype._afterBind.call(this, mesh);
  26792. this.getScene()._cachedEffect = effect;
  26793. };
  26794. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26795. if (visibility === void 0) { visibility = 1; }
  26796. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26797. };
  26798. return PushMaterial;
  26799. }(BABYLON.Material));
  26800. BABYLON.PushMaterial = PushMaterial;
  26801. })(BABYLON || (BABYLON = {}));
  26802. //# sourceMappingURL=babylon.pushMaterial.js.map
  26803. var BABYLON;
  26804. (function (BABYLON) {
  26805. var VertexData = (function () {
  26806. function VertexData() {
  26807. }
  26808. VertexData.prototype.set = function (data, kind) {
  26809. switch (kind) {
  26810. case BABYLON.VertexBuffer.PositionKind:
  26811. this.positions = data;
  26812. break;
  26813. case BABYLON.VertexBuffer.NormalKind:
  26814. this.normals = data;
  26815. break;
  26816. case BABYLON.VertexBuffer.TangentKind:
  26817. this.tangents = data;
  26818. break;
  26819. case BABYLON.VertexBuffer.UVKind:
  26820. this.uvs = data;
  26821. break;
  26822. case BABYLON.VertexBuffer.UV2Kind:
  26823. this.uvs2 = data;
  26824. break;
  26825. case BABYLON.VertexBuffer.UV3Kind:
  26826. this.uvs3 = data;
  26827. break;
  26828. case BABYLON.VertexBuffer.UV4Kind:
  26829. this.uvs4 = data;
  26830. break;
  26831. case BABYLON.VertexBuffer.UV5Kind:
  26832. this.uvs5 = data;
  26833. break;
  26834. case BABYLON.VertexBuffer.UV6Kind:
  26835. this.uvs6 = data;
  26836. break;
  26837. case BABYLON.VertexBuffer.ColorKind:
  26838. this.colors = data;
  26839. break;
  26840. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26841. this.matricesIndices = data;
  26842. break;
  26843. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26844. this.matricesWeights = data;
  26845. break;
  26846. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26847. this.matricesIndicesExtra = data;
  26848. break;
  26849. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26850. this.matricesWeightsExtra = data;
  26851. break;
  26852. }
  26853. };
  26854. /**
  26855. * Associates the vertexData to the passed Mesh.
  26856. * Sets it as updatable or not (default `false`).
  26857. * Returns the VertexData.
  26858. */
  26859. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26860. this._applyTo(mesh, updatable);
  26861. return this;
  26862. };
  26863. /**
  26864. * Associates the vertexData to the passed Geometry.
  26865. * Sets it as updatable or not (default `false`).
  26866. * Returns the VertexData.
  26867. */
  26868. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26869. this._applyTo(geometry, updatable);
  26870. return this;
  26871. };
  26872. /**
  26873. * Updates the associated mesh.
  26874. * Returns the VertexData.
  26875. */
  26876. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26877. this._update(mesh);
  26878. return this;
  26879. };
  26880. /**
  26881. * Updates the associated geometry.
  26882. * Returns the VertexData.
  26883. */
  26884. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26885. this._update(geometry);
  26886. return this;
  26887. };
  26888. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26889. if (this.positions) {
  26890. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26891. }
  26892. if (this.normals) {
  26893. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26894. }
  26895. if (this.tangents) {
  26896. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26897. }
  26898. if (this.uvs) {
  26899. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26900. }
  26901. if (this.uvs2) {
  26902. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26903. }
  26904. if (this.uvs3) {
  26905. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26906. }
  26907. if (this.uvs4) {
  26908. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26909. }
  26910. if (this.uvs5) {
  26911. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26912. }
  26913. if (this.uvs6) {
  26914. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26915. }
  26916. if (this.colors) {
  26917. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26918. }
  26919. if (this.matricesIndices) {
  26920. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26921. }
  26922. if (this.matricesWeights) {
  26923. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26924. }
  26925. if (this.matricesIndicesExtra) {
  26926. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26927. }
  26928. if (this.matricesWeightsExtra) {
  26929. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26930. }
  26931. if (this.indices) {
  26932. meshOrGeometry.setIndices(this.indices);
  26933. }
  26934. return this;
  26935. };
  26936. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26937. if (this.positions) {
  26938. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26939. }
  26940. if (this.normals) {
  26941. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26942. }
  26943. if (this.tangents) {
  26944. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26945. }
  26946. if (this.uvs) {
  26947. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26948. }
  26949. if (this.uvs2) {
  26950. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26951. }
  26952. if (this.uvs3) {
  26953. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26954. }
  26955. if (this.uvs4) {
  26956. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26957. }
  26958. if (this.uvs5) {
  26959. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26960. }
  26961. if (this.uvs6) {
  26962. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26963. }
  26964. if (this.colors) {
  26965. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26966. }
  26967. if (this.matricesIndices) {
  26968. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26969. }
  26970. if (this.matricesWeights) {
  26971. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26972. }
  26973. if (this.matricesIndicesExtra) {
  26974. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26975. }
  26976. if (this.matricesWeightsExtra) {
  26977. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26978. }
  26979. if (this.indices) {
  26980. meshOrGeometry.setIndices(this.indices);
  26981. }
  26982. return this;
  26983. };
  26984. /**
  26985. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26986. * Returns the VertexData.
  26987. */
  26988. VertexData.prototype.transform = function (matrix) {
  26989. var transformed = BABYLON.Vector3.Zero();
  26990. var index;
  26991. if (this.positions) {
  26992. var position = BABYLON.Vector3.Zero();
  26993. for (index = 0; index < this.positions.length; index += 3) {
  26994. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26995. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26996. this.positions[index] = transformed.x;
  26997. this.positions[index + 1] = transformed.y;
  26998. this.positions[index + 2] = transformed.z;
  26999. }
  27000. }
  27001. if (this.normals) {
  27002. var normal = BABYLON.Vector3.Zero();
  27003. for (index = 0; index < this.normals.length; index += 3) {
  27004. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27005. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27006. this.normals[index] = transformed.x;
  27007. this.normals[index + 1] = transformed.y;
  27008. this.normals[index + 2] = transformed.z;
  27009. }
  27010. }
  27011. if (this.tangents) {
  27012. var tangent = BABYLON.Vector4.Zero();
  27013. var tangentTransformed = BABYLON.Vector4.Zero();
  27014. for (index = 0; index < this.tangents.length; index += 4) {
  27015. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  27016. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  27017. this.tangents[index] = tangentTransformed.x;
  27018. this.tangents[index + 1] = tangentTransformed.y;
  27019. this.tangents[index + 2] = tangentTransformed.z;
  27020. this.tangents[index + 3] = tangentTransformed.w;
  27021. }
  27022. }
  27023. return this;
  27024. };
  27025. /**
  27026. * Merges the passed VertexData into the current one.
  27027. * Returns the modified VertexData.
  27028. */
  27029. VertexData.prototype.merge = function (other) {
  27030. if (other.indices) {
  27031. if (!this.indices) {
  27032. this.indices = [];
  27033. }
  27034. var offset = this.positions ? this.positions.length / 3 : 0;
  27035. for (var index = 0; index < other.indices.length; index++) {
  27036. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  27037. this.indices.push(other.indices[index] + offset);
  27038. }
  27039. }
  27040. this.positions = this._mergeElement(this.positions, other.positions);
  27041. var count = this.positions.length / 3;
  27042. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  27043. this.tangents = this._mergeElement(this.tangents, other.tangents, count * 4);
  27044. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  27045. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  27046. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  27047. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  27048. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  27049. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  27050. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  27051. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  27052. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  27053. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  27054. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  27055. return this;
  27056. };
  27057. VertexData.prototype._mergeElement = function (source, other, length) {
  27058. if (length === void 0) { length = 0; }
  27059. if (!other && !source) {
  27060. return null;
  27061. }
  27062. if (!other) {
  27063. return this._mergeElement(source, new Float32Array(source.length), length);
  27064. }
  27065. if (!source) {
  27066. if (length === other.length) {
  27067. return other;
  27068. }
  27069. return this._mergeElement(new Float32Array(length - other.length), other, length);
  27070. }
  27071. var len = other.length + source.length;
  27072. var isSrcTypedArray = source instanceof Float32Array;
  27073. var isOthTypedArray = other instanceof Float32Array;
  27074. // use non-loop method when the source is Float32Array
  27075. if (isSrcTypedArray) {
  27076. var ret32 = new Float32Array(len);
  27077. ret32.set(source);
  27078. ret32.set(other, source.length);
  27079. return ret32;
  27080. // source is number[], when other is also use concat
  27081. }
  27082. else if (!isOthTypedArray) {
  27083. return source.concat(other);
  27084. // source is a number[], but other is a Float32Array, loop required
  27085. }
  27086. else {
  27087. var ret = source.slice(0); // copy source to a separate array
  27088. for (var i = 0, len = other.length; i < len; i++) {
  27089. ret.push(other[i]);
  27090. }
  27091. return ret;
  27092. }
  27093. };
  27094. /**
  27095. * Serializes the VertexData.
  27096. * Returns a serialized object.
  27097. */
  27098. VertexData.prototype.serialize = function () {
  27099. var serializationObject = this.serialize();
  27100. if (this.positions) {
  27101. serializationObject.positions = this.positions;
  27102. }
  27103. if (this.normals) {
  27104. serializationObject.normals = this.normals;
  27105. }
  27106. if (this.tangents) {
  27107. serializationObject.tangents = this.tangents;
  27108. }
  27109. if (this.uvs) {
  27110. serializationObject.uvs = this.uvs;
  27111. }
  27112. if (this.uvs2) {
  27113. serializationObject.uvs2 = this.uvs2;
  27114. }
  27115. if (this.uvs3) {
  27116. serializationObject.uvs3 = this.uvs3;
  27117. }
  27118. if (this.uvs4) {
  27119. serializationObject.uvs4 = this.uvs4;
  27120. }
  27121. if (this.uvs5) {
  27122. serializationObject.uvs5 = this.uvs5;
  27123. }
  27124. if (this.uvs6) {
  27125. serializationObject.uvs6 = this.uvs6;
  27126. }
  27127. if (this.colors) {
  27128. serializationObject.colors = this.colors;
  27129. }
  27130. if (this.matricesIndices) {
  27131. serializationObject.matricesIndices = this.matricesIndices;
  27132. serializationObject.matricesIndices._isExpanded = true;
  27133. }
  27134. if (this.matricesWeights) {
  27135. serializationObject.matricesWeights = this.matricesWeights;
  27136. }
  27137. if (this.matricesIndicesExtra) {
  27138. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27139. serializationObject.matricesIndicesExtra._isExpanded = true;
  27140. }
  27141. if (this.matricesWeightsExtra) {
  27142. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27143. }
  27144. serializationObject.indices = this.indices;
  27145. return serializationObject;
  27146. };
  27147. // Statics
  27148. /**
  27149. * Returns the object VertexData associated to the passed mesh.
  27150. */
  27151. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  27152. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  27153. };
  27154. /**
  27155. * Returns the object VertexData associated to the passed geometry.
  27156. */
  27157. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  27158. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  27159. };
  27160. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  27161. var result = new VertexData();
  27162. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27163. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  27164. }
  27165. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27166. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  27167. }
  27168. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  27169. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  27170. }
  27171. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27172. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  27173. }
  27174. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27175. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  27176. }
  27177. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27178. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  27179. }
  27180. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27181. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  27182. }
  27183. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27184. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  27185. }
  27186. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27187. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  27188. }
  27189. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27190. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  27191. }
  27192. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27193. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  27194. }
  27195. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27196. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  27197. }
  27198. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27199. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  27200. }
  27201. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27202. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  27203. }
  27204. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27205. return result;
  27206. };
  27207. /**
  27208. * Creates the vertexData of the Ribbon.
  27209. */
  27210. VertexData.CreateRibbon = function (options) {
  27211. var pathArray = options.pathArray;
  27212. var closeArray = options.closeArray || false;
  27213. var closePath = options.closePath || false;
  27214. var invertUV = options.invertUV || false;
  27215. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27216. var offset = options.offset || defaultOffset;
  27217. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27218. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27219. var customUV = options.uvs;
  27220. var customColors = options.colors;
  27221. var positions = [];
  27222. var indices = [];
  27223. var normals = [];
  27224. var uvs = [];
  27225. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27226. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27227. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27228. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27229. var minlg; // minimal length among all paths from pathArray
  27230. var lg = []; // array of path lengths : nb of vertex per path
  27231. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27232. var p; // path iterator
  27233. var i; // point iterator
  27234. var j; // point iterator
  27235. // if single path in pathArray
  27236. if (pathArray.length < 2) {
  27237. var ar1 = [];
  27238. var ar2 = [];
  27239. for (i = 0; i < pathArray[0].length - offset; i++) {
  27240. ar1.push(pathArray[0][i]);
  27241. ar2.push(pathArray[0][i + offset]);
  27242. }
  27243. pathArray = [ar1, ar2];
  27244. }
  27245. // positions and horizontal distances (u)
  27246. var idc = 0;
  27247. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  27248. var path;
  27249. var l;
  27250. minlg = pathArray[0].length;
  27251. var vectlg;
  27252. var dist;
  27253. for (p = 0; p < pathArray.length; p++) {
  27254. uTotalDistance[p] = 0;
  27255. us[p] = [0];
  27256. path = pathArray[p];
  27257. l = path.length;
  27258. minlg = (minlg < l) ? minlg : l;
  27259. j = 0;
  27260. while (j < l) {
  27261. positions.push(path[j].x, path[j].y, path[j].z);
  27262. if (j > 0) {
  27263. vectlg = path[j].subtract(path[j - 1]).length();
  27264. dist = vectlg + uTotalDistance[p];
  27265. us[p].push(dist);
  27266. uTotalDistance[p] = dist;
  27267. }
  27268. j++;
  27269. }
  27270. if (closePath) {
  27271. j--;
  27272. positions.push(path[0].x, path[0].y, path[0].z);
  27273. vectlg = path[j].subtract(path[0]).length();
  27274. dist = vectlg + uTotalDistance[p];
  27275. us[p].push(dist);
  27276. uTotalDistance[p] = dist;
  27277. }
  27278. lg[p] = l + closePathCorr;
  27279. idx[p] = idc;
  27280. idc += (l + closePathCorr);
  27281. }
  27282. // vertical distances (v)
  27283. var path1;
  27284. var path2;
  27285. var vertex1;
  27286. var vertex2;
  27287. for (i = 0; i < minlg + closePathCorr; i++) {
  27288. vTotalDistance[i] = 0;
  27289. vs[i] = [0];
  27290. for (p = 0; p < pathArray.length - 1; p++) {
  27291. path1 = pathArray[p];
  27292. path2 = pathArray[p + 1];
  27293. if (i === minlg) {
  27294. vertex1 = path1[0];
  27295. vertex2 = path2[0];
  27296. }
  27297. else {
  27298. vertex1 = path1[i];
  27299. vertex2 = path2[i];
  27300. }
  27301. vectlg = vertex2.subtract(vertex1).length();
  27302. dist = vectlg + vTotalDistance[i];
  27303. vs[i].push(dist);
  27304. vTotalDistance[i] = dist;
  27305. }
  27306. if (closeArray) {
  27307. path1 = pathArray[p];
  27308. path2 = pathArray[0];
  27309. if (i === minlg) {
  27310. vertex2 = path2[0];
  27311. }
  27312. vectlg = vertex2.subtract(vertex1).length();
  27313. dist = vectlg + vTotalDistance[i];
  27314. vTotalDistance[i] = dist;
  27315. }
  27316. }
  27317. // uvs
  27318. var u;
  27319. var v;
  27320. if (customUV) {
  27321. for (p = 0; p < customUV.length; p++) {
  27322. uvs.push(customUV[p].x, customUV[p].y);
  27323. }
  27324. }
  27325. else {
  27326. for (p = 0; p < pathArray.length; p++) {
  27327. for (i = 0; i < minlg + closePathCorr; i++) {
  27328. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  27329. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  27330. if (invertUV) {
  27331. uvs.push(v, u);
  27332. }
  27333. else {
  27334. uvs.push(u, v);
  27335. }
  27336. }
  27337. }
  27338. }
  27339. // indices
  27340. p = 0; // path index
  27341. var pi = 0; // positions array index
  27342. var l1 = lg[p] - 1; // path1 length
  27343. var l2 = lg[p + 1] - 1; // path2 length
  27344. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27345. var shft = idx[1] - idx[0]; // shift
  27346. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27347. while (pi <= min && p < path1nb) {
  27348. // 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
  27349. indices.push(pi, pi + shft, pi + 1);
  27350. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27351. pi += 1;
  27352. if (pi === min) {
  27353. p++;
  27354. if (p === lg.length - 1) {
  27355. shft = idx[0] - idx[p];
  27356. l1 = lg[p] - 1;
  27357. l2 = lg[0] - 1;
  27358. }
  27359. else {
  27360. shft = idx[p + 1] - idx[p];
  27361. l1 = lg[p] - 1;
  27362. l2 = lg[p + 1] - 1;
  27363. }
  27364. pi = idx[p];
  27365. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27366. }
  27367. }
  27368. // normals
  27369. VertexData.ComputeNormals(positions, indices, normals);
  27370. if (closePath) {
  27371. var indexFirst = 0;
  27372. var indexLast = 0;
  27373. for (p = 0; p < pathArray.length; p++) {
  27374. indexFirst = idx[p] * 3;
  27375. if (p + 1 < pathArray.length) {
  27376. indexLast = (idx[p + 1] - 1) * 3;
  27377. }
  27378. else {
  27379. indexLast = normals.length - 3;
  27380. }
  27381. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27382. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27383. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27384. normals[indexLast] = normals[indexFirst];
  27385. normals[indexLast + 1] = normals[indexFirst + 1];
  27386. normals[indexLast + 2] = normals[indexFirst + 2];
  27387. }
  27388. }
  27389. // sides
  27390. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27391. // Colors
  27392. if (customColors) {
  27393. var colors = new Float32Array(customColors.length * 4);
  27394. for (var c = 0; c < customColors.length; c++) {
  27395. colors[c * 4] = customColors[c].r;
  27396. colors[c * 4 + 1] = customColors[c].g;
  27397. colors[c * 4 + 2] = customColors[c].b;
  27398. colors[c * 4 + 3] = customColors[c].a;
  27399. }
  27400. }
  27401. // Result
  27402. var vertexData = new VertexData();
  27403. var positions32 = new Float32Array(positions);
  27404. var normals32 = new Float32Array(normals);
  27405. var uvs32 = new Float32Array(uvs);
  27406. vertexData.indices = indices;
  27407. vertexData.positions = positions32;
  27408. vertexData.normals = normals32;
  27409. vertexData.uvs = uvs32;
  27410. if (customColors) {
  27411. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  27412. }
  27413. if (closePath) {
  27414. vertexData._idx = idx;
  27415. }
  27416. return vertexData;
  27417. };
  27418. /**
  27419. * Creates the VertexData of the Box.
  27420. */
  27421. VertexData.CreateBox = function (options) {
  27422. var normalsSource = [
  27423. new BABYLON.Vector3(0, 0, 1),
  27424. new BABYLON.Vector3(0, 0, -1),
  27425. new BABYLON.Vector3(1, 0, 0),
  27426. new BABYLON.Vector3(-1, 0, 0),
  27427. new BABYLON.Vector3(0, 1, 0),
  27428. new BABYLON.Vector3(0, -1, 0)
  27429. ];
  27430. var indices = [];
  27431. var positions = [];
  27432. var normals = [];
  27433. var uvs = [];
  27434. var width = options.width || options.size || 1;
  27435. var height = options.height || options.size || 1;
  27436. var depth = options.depth || options.size || 1;
  27437. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27438. var faceUV = options.faceUV || new Array(6);
  27439. var faceColors = options.faceColors;
  27440. var colors = [];
  27441. // default face colors and UV if undefined
  27442. for (var f = 0; f < 6; f++) {
  27443. if (faceUV[f] === undefined) {
  27444. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27445. }
  27446. if (faceColors && faceColors[f] === undefined) {
  27447. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27448. }
  27449. }
  27450. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27451. // Create each face in turn.
  27452. for (var index = 0; index < normalsSource.length; index++) {
  27453. var normal = normalsSource[index];
  27454. // Get two vectors perpendicular to the face normal and to each other.
  27455. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27456. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27457. // Six indices (two triangles) per face.
  27458. var verticesLength = positions.length / 3;
  27459. indices.push(verticesLength);
  27460. indices.push(verticesLength + 1);
  27461. indices.push(verticesLength + 2);
  27462. indices.push(verticesLength);
  27463. indices.push(verticesLength + 2);
  27464. indices.push(verticesLength + 3);
  27465. // Four vertices per face.
  27466. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27467. positions.push(vertex.x, vertex.y, vertex.z);
  27468. normals.push(normal.x, normal.y, normal.z);
  27469. uvs.push(faceUV[index].z, faceUV[index].w);
  27470. if (faceColors) {
  27471. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27472. }
  27473. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27474. positions.push(vertex.x, vertex.y, vertex.z);
  27475. normals.push(normal.x, normal.y, normal.z);
  27476. uvs.push(faceUV[index].x, faceUV[index].w);
  27477. if (faceColors) {
  27478. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27479. }
  27480. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27481. positions.push(vertex.x, vertex.y, vertex.z);
  27482. normals.push(normal.x, normal.y, normal.z);
  27483. uvs.push(faceUV[index].x, faceUV[index].y);
  27484. if (faceColors) {
  27485. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27486. }
  27487. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27488. positions.push(vertex.x, vertex.y, vertex.z);
  27489. normals.push(normal.x, normal.y, normal.z);
  27490. uvs.push(faceUV[index].z, faceUV[index].y);
  27491. if (faceColors) {
  27492. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27493. }
  27494. }
  27495. // sides
  27496. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27497. // Result
  27498. var vertexData = new VertexData();
  27499. vertexData.indices = indices;
  27500. vertexData.positions = positions;
  27501. vertexData.normals = normals;
  27502. vertexData.uvs = uvs;
  27503. if (faceColors) {
  27504. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27505. vertexData.colors = totalColors;
  27506. }
  27507. return vertexData;
  27508. };
  27509. /**
  27510. * Creates the VertexData of the Sphere.
  27511. */
  27512. VertexData.CreateSphere = function (options) {
  27513. var segments = options.segments || 32;
  27514. var diameterX = options.diameterX || options.diameter || 1;
  27515. var diameterY = options.diameterY || options.diameter || 1;
  27516. var diameterZ = options.diameterZ || options.diameter || 1;
  27517. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27518. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27519. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27520. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27521. var totalZRotationSteps = 2 + segments;
  27522. var totalYRotationSteps = 2 * totalZRotationSteps;
  27523. var indices = [];
  27524. var positions = [];
  27525. var normals = [];
  27526. var uvs = [];
  27527. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27528. var normalizedZ = zRotationStep / totalZRotationSteps;
  27529. var angleZ = normalizedZ * Math.PI * slice;
  27530. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27531. var normalizedY = yRotationStep / totalYRotationSteps;
  27532. var angleY = normalizedY * Math.PI * 2 * arc;
  27533. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27534. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27535. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27536. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27537. var vertex = complete.multiply(radius);
  27538. var normal = complete.divide(radius).normalize();
  27539. positions.push(vertex.x, vertex.y, vertex.z);
  27540. normals.push(normal.x, normal.y, normal.z);
  27541. uvs.push(normalizedY, normalizedZ);
  27542. }
  27543. if (zRotationStep > 0) {
  27544. var verticesCount = positions.length / 3;
  27545. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27546. indices.push((firstIndex));
  27547. indices.push((firstIndex + 1));
  27548. indices.push(firstIndex + totalYRotationSteps + 1);
  27549. indices.push((firstIndex + totalYRotationSteps + 1));
  27550. indices.push((firstIndex + 1));
  27551. indices.push((firstIndex + totalYRotationSteps + 2));
  27552. }
  27553. }
  27554. }
  27555. // Sides
  27556. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27557. // Result
  27558. var vertexData = new VertexData();
  27559. vertexData.indices = indices;
  27560. vertexData.positions = positions;
  27561. vertexData.normals = normals;
  27562. vertexData.uvs = uvs;
  27563. return vertexData;
  27564. };
  27565. /**
  27566. * Creates the VertexData of the Cylinder or Cone.
  27567. */
  27568. VertexData.CreateCylinder = function (options) {
  27569. var height = options.height || 2;
  27570. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27571. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27572. var tessellation = options.tessellation || 24;
  27573. var subdivisions = options.subdivisions || 1;
  27574. var hasRings = options.hasRings;
  27575. var enclose = options.enclose;
  27576. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27577. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27578. var faceUV = options.faceUV || new Array(3);
  27579. var faceColors = options.faceColors;
  27580. // default face colors and UV if undefined
  27581. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27582. var ringNb = (hasRings) ? subdivisions : 1;
  27583. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27584. var f;
  27585. for (f = 0; f < surfaceNb; f++) {
  27586. if (faceColors && faceColors[f] === undefined) {
  27587. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27588. }
  27589. }
  27590. for (f = 0; f < surfaceNb; f++) {
  27591. if (faceUV && faceUV[f] === undefined) {
  27592. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27593. }
  27594. }
  27595. var indices = [];
  27596. var positions = [];
  27597. var normals = [];
  27598. var uvs = [];
  27599. var colors = [];
  27600. var angle_step = Math.PI * 2 * arc / tessellation;
  27601. var angle;
  27602. var h;
  27603. var radius;
  27604. var tan = (diameterBottom - diameterTop) / 2 / height;
  27605. var ringVertex = BABYLON.Vector3.Zero();
  27606. var ringNormal = BABYLON.Vector3.Zero();
  27607. var ringFirstVertex = BABYLON.Vector3.Zero();
  27608. var ringFirstNormal = BABYLON.Vector3.Zero();
  27609. var quadNormal = BABYLON.Vector3.Zero();
  27610. var Y = BABYLON.Axis.Y;
  27611. // positions, normals, uvs
  27612. var i;
  27613. var j;
  27614. var r;
  27615. var ringIdx = 1;
  27616. var s = 1; // surface index
  27617. var cs = 0;
  27618. var v = 0;
  27619. for (i = 0; i <= subdivisions; i++) {
  27620. h = i / subdivisions;
  27621. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27622. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27623. for (r = 0; r < ringIdx; r++) {
  27624. if (hasRings) {
  27625. s += r;
  27626. }
  27627. if (enclose) {
  27628. s += 2 * r;
  27629. }
  27630. for (j = 0; j <= tessellation; j++) {
  27631. angle = j * angle_step;
  27632. // position
  27633. ringVertex.x = Math.cos(-angle) * radius;
  27634. ringVertex.y = -height / 2 + h * height;
  27635. ringVertex.z = Math.sin(-angle) * radius;
  27636. // normal
  27637. if (diameterTop === 0 && i === subdivisions) {
  27638. // if no top cap, reuse former normals
  27639. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27640. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27641. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27642. }
  27643. else {
  27644. ringNormal.x = ringVertex.x;
  27645. ringNormal.z = ringVertex.z;
  27646. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27647. ringNormal.normalize();
  27648. }
  27649. // keep first ring vertex values for enclose
  27650. if (j === 0) {
  27651. ringFirstVertex.copyFrom(ringVertex);
  27652. ringFirstNormal.copyFrom(ringNormal);
  27653. }
  27654. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27655. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27656. if (hasRings) {
  27657. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27658. }
  27659. else {
  27660. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27661. }
  27662. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27663. if (faceColors) {
  27664. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27665. }
  27666. }
  27667. // if enclose, add four vertices and their dedicated normals
  27668. if (arc !== 1 && enclose) {
  27669. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27670. positions.push(0, ringVertex.y, 0);
  27671. positions.push(0, ringVertex.y, 0);
  27672. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27673. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27674. quadNormal.normalize();
  27675. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27676. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27677. quadNormal.normalize();
  27678. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27679. if (hasRings) {
  27680. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27681. }
  27682. else {
  27683. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27684. }
  27685. uvs.push(faceUV[s + 1].x, v);
  27686. uvs.push(faceUV[s + 1].z, v);
  27687. if (hasRings) {
  27688. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27689. }
  27690. else {
  27691. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27692. }
  27693. uvs.push(faceUV[s + 2].x, v);
  27694. uvs.push(faceUV[s + 2].z, v);
  27695. if (faceColors) {
  27696. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27697. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27698. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27699. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27700. }
  27701. }
  27702. if (cs !== s) {
  27703. cs = s;
  27704. }
  27705. }
  27706. }
  27707. // indices
  27708. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27709. var s;
  27710. i = 0;
  27711. for (s = 0; s < subdivisions; s++) {
  27712. for (j = 0; j < tessellation; j++) {
  27713. var i0 = i * (e + 1) + j;
  27714. var i1 = (i + 1) * (e + 1) + j;
  27715. var i2 = i * (e + 1) + (j + 1);
  27716. var i3 = (i + 1) * (e + 1) + (j + 1);
  27717. indices.push(i0, i1, i2);
  27718. indices.push(i3, i2, i1);
  27719. }
  27720. if (arc !== 1 && enclose) {
  27721. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27722. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27723. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27724. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27725. }
  27726. i = (hasRings) ? (i + 2) : (i + 1);
  27727. }
  27728. // Caps
  27729. var createCylinderCap = function (isTop) {
  27730. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27731. if (radius === 0) {
  27732. return;
  27733. }
  27734. // Cap positions, normals & uvs
  27735. var angle;
  27736. var circleVector;
  27737. var i;
  27738. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27739. var c;
  27740. if (faceColors) {
  27741. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27742. }
  27743. // cap center
  27744. var vbase = positions.length / 3;
  27745. var offset = isTop ? height / 2 : -height / 2;
  27746. var center = new BABYLON.Vector3(0, offset, 0);
  27747. positions.push(center.x, center.y, center.z);
  27748. normals.push(0, isTop ? 1 : -1, 0);
  27749. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27750. if (faceColors) {
  27751. colors.push(c.r, c.g, c.b, c.a);
  27752. }
  27753. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27754. for (i = 0; i <= tessellation; i++) {
  27755. angle = Math.PI * 2 * i * arc / tessellation;
  27756. var cos = Math.cos(-angle);
  27757. var sin = Math.sin(-angle);
  27758. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27759. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27760. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27761. normals.push(0, isTop ? 1 : -1, 0);
  27762. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27763. if (faceColors) {
  27764. colors.push(c.r, c.g, c.b, c.a);
  27765. }
  27766. }
  27767. // Cap indices
  27768. for (i = 0; i < tessellation; i++) {
  27769. if (!isTop) {
  27770. indices.push(vbase);
  27771. indices.push(vbase + (i + 1));
  27772. indices.push(vbase + (i + 2));
  27773. }
  27774. else {
  27775. indices.push(vbase);
  27776. indices.push(vbase + (i + 2));
  27777. indices.push(vbase + (i + 1));
  27778. }
  27779. }
  27780. };
  27781. // add caps to geometry
  27782. createCylinderCap(false);
  27783. createCylinderCap(true);
  27784. // Sides
  27785. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27786. var vertexData = new VertexData();
  27787. vertexData.indices = indices;
  27788. vertexData.positions = positions;
  27789. vertexData.normals = normals;
  27790. vertexData.uvs = uvs;
  27791. if (faceColors) {
  27792. vertexData.colors = colors;
  27793. }
  27794. return vertexData;
  27795. };
  27796. /**
  27797. * Creates the VertexData of the Torus.
  27798. */
  27799. VertexData.CreateTorus = function (options) {
  27800. var indices = [];
  27801. var positions = [];
  27802. var normals = [];
  27803. var uvs = [];
  27804. var diameter = options.diameter || 1;
  27805. var thickness = options.thickness || 0.5;
  27806. var tessellation = options.tessellation || 16;
  27807. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27808. var stride = tessellation + 1;
  27809. for (var i = 0; i <= tessellation; i++) {
  27810. var u = i / tessellation;
  27811. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27812. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27813. for (var j = 0; j <= tessellation; j++) {
  27814. var v = 1 - j / tessellation;
  27815. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27816. var dx = Math.cos(innerAngle);
  27817. var dy = Math.sin(innerAngle);
  27818. // Create a vertex.
  27819. var normal = new BABYLON.Vector3(dx, dy, 0);
  27820. var position = normal.scale(thickness / 2);
  27821. var textureCoordinate = new BABYLON.Vector2(u, v);
  27822. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27823. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27824. positions.push(position.x, position.y, position.z);
  27825. normals.push(normal.x, normal.y, normal.z);
  27826. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27827. // And create indices for two triangles.
  27828. var nextI = (i + 1) % stride;
  27829. var nextJ = (j + 1) % stride;
  27830. indices.push(i * stride + j);
  27831. indices.push(i * stride + nextJ);
  27832. indices.push(nextI * stride + j);
  27833. indices.push(i * stride + nextJ);
  27834. indices.push(nextI * stride + nextJ);
  27835. indices.push(nextI * stride + j);
  27836. }
  27837. }
  27838. // Sides
  27839. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27840. // Result
  27841. var vertexData = new VertexData();
  27842. vertexData.indices = indices;
  27843. vertexData.positions = positions;
  27844. vertexData.normals = normals;
  27845. vertexData.uvs = uvs;
  27846. return vertexData;
  27847. };
  27848. /**
  27849. * Creates the VertexData of the LineSystem.
  27850. */
  27851. VertexData.CreateLineSystem = function (options) {
  27852. var indices = [];
  27853. var positions = [];
  27854. var lines = options.lines;
  27855. var idx = 0;
  27856. for (var l = 0; l < lines.length; l++) {
  27857. var points = lines[l];
  27858. for (var index = 0; index < points.length; index++) {
  27859. positions.push(points[index].x, points[index].y, points[index].z);
  27860. if (index > 0) {
  27861. indices.push(idx - 1);
  27862. indices.push(idx);
  27863. }
  27864. idx++;
  27865. }
  27866. }
  27867. var vertexData = new VertexData();
  27868. vertexData.indices = indices;
  27869. vertexData.positions = positions;
  27870. return vertexData;
  27871. };
  27872. /**
  27873. * Create the VertexData of the DashedLines.
  27874. */
  27875. VertexData.CreateDashedLines = function (options) {
  27876. var dashSize = options.dashSize || 3;
  27877. var gapSize = options.gapSize || 1;
  27878. var dashNb = options.dashNb || 200;
  27879. var points = options.points;
  27880. var positions = new Array();
  27881. var indices = new Array();
  27882. var curvect = BABYLON.Vector3.Zero();
  27883. var lg = 0;
  27884. var nb = 0;
  27885. var shft = 0;
  27886. var dashshft = 0;
  27887. var curshft = 0;
  27888. var idx = 0;
  27889. var i = 0;
  27890. for (i = 0; i < points.length - 1; i++) {
  27891. points[i + 1].subtractToRef(points[i], curvect);
  27892. lg += curvect.length();
  27893. }
  27894. shft = lg / dashNb;
  27895. dashshft = dashSize * shft / (dashSize + gapSize);
  27896. for (i = 0; i < points.length - 1; i++) {
  27897. points[i + 1].subtractToRef(points[i], curvect);
  27898. nb = Math.floor(curvect.length() / shft);
  27899. curvect.normalize();
  27900. for (var j = 0; j < nb; j++) {
  27901. curshft = shft * j;
  27902. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27903. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27904. indices.push(idx, idx + 1);
  27905. idx += 2;
  27906. }
  27907. }
  27908. // Result
  27909. var vertexData = new VertexData();
  27910. vertexData.positions = positions;
  27911. vertexData.indices = indices;
  27912. return vertexData;
  27913. };
  27914. /**
  27915. * Creates the VertexData of the Ground.
  27916. */
  27917. VertexData.CreateGround = function (options) {
  27918. var indices = [];
  27919. var positions = [];
  27920. var normals = [];
  27921. var uvs = [];
  27922. var row, col;
  27923. var width = options.width || 1;
  27924. var height = options.height || 1;
  27925. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27926. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27927. for (row = 0; row <= subdivisionsY; row++) {
  27928. for (col = 0; col <= subdivisionsX; col++) {
  27929. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27930. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27931. positions.push(position.x, position.y, position.z);
  27932. normals.push(normal.x, normal.y, normal.z);
  27933. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27934. }
  27935. }
  27936. for (row = 0; row < subdivisionsY; row++) {
  27937. for (col = 0; col < subdivisionsX; col++) {
  27938. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27939. indices.push(col + 1 + row * (subdivisionsX + 1));
  27940. indices.push(col + row * (subdivisionsX + 1));
  27941. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27942. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27943. indices.push(col + row * (subdivisionsX + 1));
  27944. }
  27945. }
  27946. // Result
  27947. var vertexData = new VertexData();
  27948. vertexData.indices = indices;
  27949. vertexData.positions = positions;
  27950. vertexData.normals = normals;
  27951. vertexData.uvs = uvs;
  27952. return vertexData;
  27953. };
  27954. /**
  27955. * Creates the VertexData of the TiledGround.
  27956. */
  27957. VertexData.CreateTiledGround = function (options) {
  27958. var xmin = options.xmin || -1.0;
  27959. var zmin = options.zmin || -1.0;
  27960. var xmax = options.xmax || 1.0;
  27961. var zmax = options.zmax || 1.0;
  27962. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27963. var precision = options.precision || { w: 1, h: 1 };
  27964. var indices = [];
  27965. var positions = [];
  27966. var normals = [];
  27967. var uvs = [];
  27968. var row, col, tileRow, tileCol;
  27969. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27970. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27971. precision.w = (precision.w < 1) ? 1 : precision.w;
  27972. precision.h = (precision.h < 1) ? 1 : precision.h;
  27973. var tileSize = {
  27974. 'w': (xmax - xmin) / subdivisions.w,
  27975. 'h': (zmax - zmin) / subdivisions.h
  27976. };
  27977. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27978. // Indices
  27979. var base = positions.length / 3;
  27980. var rowLength = precision.w + 1;
  27981. for (row = 0; row < precision.h; row++) {
  27982. for (col = 0; col < precision.w; col++) {
  27983. var square = [
  27984. base + col + row * rowLength,
  27985. base + (col + 1) + row * rowLength,
  27986. base + (col + 1) + (row + 1) * rowLength,
  27987. base + col + (row + 1) * rowLength
  27988. ];
  27989. indices.push(square[1]);
  27990. indices.push(square[2]);
  27991. indices.push(square[3]);
  27992. indices.push(square[0]);
  27993. indices.push(square[1]);
  27994. indices.push(square[3]);
  27995. }
  27996. }
  27997. // Position, normals and uvs
  27998. var position = BABYLON.Vector3.Zero();
  27999. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28000. for (row = 0; row <= precision.h; row++) {
  28001. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28002. for (col = 0; col <= precision.w; col++) {
  28003. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28004. position.y = 0;
  28005. positions.push(position.x, position.y, position.z);
  28006. normals.push(normal.x, normal.y, normal.z);
  28007. uvs.push(col / precision.w, row / precision.h);
  28008. }
  28009. }
  28010. }
  28011. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28012. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28013. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28014. }
  28015. }
  28016. // Result
  28017. var vertexData = new VertexData();
  28018. vertexData.indices = indices;
  28019. vertexData.positions = positions;
  28020. vertexData.normals = normals;
  28021. vertexData.uvs = uvs;
  28022. return vertexData;
  28023. };
  28024. /**
  28025. * Creates the VertexData of the Ground designed from a heightmap.
  28026. */
  28027. VertexData.CreateGroundFromHeightMap = function (options) {
  28028. var indices = [];
  28029. var positions = [];
  28030. var normals = [];
  28031. var uvs = [];
  28032. var row, col;
  28033. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  28034. // Vertices
  28035. for (row = 0; row <= options.subdivisions; row++) {
  28036. for (col = 0; col <= options.subdivisions; col++) {
  28037. 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));
  28038. // Compute height
  28039. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28040. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28041. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28042. var r = options.buffer[pos] / 255.0;
  28043. var g = options.buffer[pos + 1] / 255.0;
  28044. var b = options.buffer[pos + 2] / 255.0;
  28045. var gradient = r * filter.r + g * filter.g + b * filter.b;
  28046. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28047. // Add vertex
  28048. positions.push(position.x, position.y, position.z);
  28049. normals.push(0, 0, 0);
  28050. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28051. }
  28052. }
  28053. // Indices
  28054. for (row = 0; row < options.subdivisions; row++) {
  28055. for (col = 0; col < options.subdivisions; col++) {
  28056. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28057. indices.push(col + 1 + row * (options.subdivisions + 1));
  28058. indices.push(col + row * (options.subdivisions + 1));
  28059. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28060. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28061. indices.push(col + row * (options.subdivisions + 1));
  28062. }
  28063. }
  28064. // Normals
  28065. VertexData.ComputeNormals(positions, indices, normals);
  28066. // Result
  28067. var vertexData = new VertexData();
  28068. vertexData.indices = indices;
  28069. vertexData.positions = positions;
  28070. vertexData.normals = normals;
  28071. vertexData.uvs = uvs;
  28072. return vertexData;
  28073. };
  28074. /**
  28075. * Creates the VertexData of the Plane.
  28076. */
  28077. VertexData.CreatePlane = function (options) {
  28078. var indices = [];
  28079. var positions = [];
  28080. var normals = [];
  28081. var uvs = [];
  28082. var width = options.width || options.size || 1;
  28083. var height = options.height || options.size || 1;
  28084. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28085. // Vertices
  28086. var halfWidth = width / 2.0;
  28087. var halfHeight = height / 2.0;
  28088. positions.push(-halfWidth, -halfHeight, 0);
  28089. normals.push(0, 0, -1.0);
  28090. uvs.push(0.0, 0.0);
  28091. positions.push(halfWidth, -halfHeight, 0);
  28092. normals.push(0, 0, -1.0);
  28093. uvs.push(1.0, 0.0);
  28094. positions.push(halfWidth, halfHeight, 0);
  28095. normals.push(0, 0, -1.0);
  28096. uvs.push(1.0, 1.0);
  28097. positions.push(-halfWidth, halfHeight, 0);
  28098. normals.push(0, 0, -1.0);
  28099. uvs.push(0.0, 1.0);
  28100. // Indices
  28101. indices.push(0);
  28102. indices.push(1);
  28103. indices.push(2);
  28104. indices.push(0);
  28105. indices.push(2);
  28106. indices.push(3);
  28107. // Sides
  28108. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28109. // Result
  28110. var vertexData = new VertexData();
  28111. vertexData.indices = indices;
  28112. vertexData.positions = positions;
  28113. vertexData.normals = normals;
  28114. vertexData.uvs = uvs;
  28115. return vertexData;
  28116. };
  28117. /**
  28118. * Creates the VertexData of the Disc or regular Polygon.
  28119. */
  28120. VertexData.CreateDisc = function (options) {
  28121. var positions = [];
  28122. var indices = [];
  28123. var normals = [];
  28124. var uvs = [];
  28125. var radius = options.radius || 0.5;
  28126. var tessellation = options.tessellation || 64;
  28127. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28128. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28129. // positions and uvs
  28130. positions.push(0, 0, 0); // disc center first
  28131. uvs.push(0.5, 0.5);
  28132. var theta = Math.PI * 2 * arc;
  28133. var step = theta / tessellation;
  28134. for (var a = 0; a < theta; a += step) {
  28135. var x = Math.cos(a);
  28136. var y = Math.sin(a);
  28137. var u = (x + 1) / 2;
  28138. var v = (1 - y) / 2;
  28139. positions.push(radius * x, radius * y, 0);
  28140. uvs.push(u, v);
  28141. }
  28142. if (arc === 1) {
  28143. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28144. uvs.push(uvs[2], uvs[3]);
  28145. }
  28146. //indices
  28147. var vertexNb = positions.length / 3;
  28148. for (var i = 1; i < vertexNb - 1; i++) {
  28149. indices.push(i + 1, 0, i);
  28150. }
  28151. // result
  28152. VertexData.ComputeNormals(positions, indices, normals);
  28153. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28154. var vertexData = new VertexData();
  28155. vertexData.indices = indices;
  28156. vertexData.positions = positions;
  28157. vertexData.normals = normals;
  28158. vertexData.uvs = uvs;
  28159. return vertexData;
  28160. };
  28161. /**
  28162. * Re-creates the VertexData of the Polygon for sideOrientation.
  28163. */
  28164. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  28165. var faceUV = fUV || new Array(3);
  28166. var faceColors = fColors;
  28167. var colors = [];
  28168. // default face colors and UV if undefined
  28169. for (var f = 0; f < 3; f++) {
  28170. if (faceUV[f] === undefined) {
  28171. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28172. }
  28173. if (faceColors && faceColors[f] === undefined) {
  28174. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28175. }
  28176. }
  28177. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28178. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28179. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28180. var indices = polygon.getIndices();
  28181. // set face colours and textures
  28182. var idx = 0;
  28183. var face = 0;
  28184. for (var index = 0; index < normals.length; index += 3) {
  28185. //Edge Face no. 1
  28186. if (Math.abs(normals[index + 1]) < 0.001) {
  28187. face = 1;
  28188. }
  28189. //Top Face no. 0
  28190. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  28191. face = 0;
  28192. }
  28193. //Bottom Face no. 2
  28194. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  28195. face = 2;
  28196. }
  28197. idx = index / 3;
  28198. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  28199. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  28200. if (faceColors) {
  28201. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  28202. }
  28203. }
  28204. // sides
  28205. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  28206. // Result
  28207. var vertexData = new VertexData();
  28208. vertexData.indices = indices;
  28209. vertexData.positions = positions;
  28210. vertexData.normals = normals;
  28211. vertexData.uvs = uvs;
  28212. if (faceColors) {
  28213. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28214. vertexData.colors = totalColors;
  28215. }
  28216. return vertexData;
  28217. };
  28218. /**
  28219. * Creates the VertexData of the IcoSphere.
  28220. */
  28221. VertexData.CreateIcoSphere = function (options) {
  28222. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28223. var radius = options.radius || 1;
  28224. var flat = (options.flat === undefined) ? true : options.flat;
  28225. var subdivisions = options.subdivisions || 4;
  28226. var radiusX = options.radiusX || radius;
  28227. var radiusY = options.radiusY || radius;
  28228. var radiusZ = options.radiusZ || radius;
  28229. var t = (1 + Math.sqrt(5)) / 2;
  28230. // 12 vertex x,y,z
  28231. var ico_vertices = [
  28232. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28233. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28234. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28235. ];
  28236. // index of 3 vertex makes a face of icopshere
  28237. var ico_indices = [
  28238. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28239. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28240. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28241. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28242. ];
  28243. // vertex for uv have aliased position, not for UV
  28244. var vertices_unalias_id = [
  28245. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28246. // vertex alias
  28247. 0,
  28248. 2,
  28249. 3,
  28250. 3,
  28251. 3,
  28252. 4,
  28253. 7,
  28254. 8,
  28255. 9,
  28256. 9,
  28257. 10,
  28258. 11 // 23: B + 12
  28259. ];
  28260. // uv as integer step (not pixels !)
  28261. var ico_vertexuv = [
  28262. 5, 1, 3, 1, 6, 4, 0, 0,
  28263. 5, 3, 4, 2, 2, 2, 4, 0,
  28264. 2, 0, 1, 1, 6, 0, 6, 2,
  28265. // vertex alias (for same vertex on different faces)
  28266. 0, 4,
  28267. 3, 3,
  28268. 4, 4,
  28269. 3, 1,
  28270. 4, 2,
  28271. 4, 4,
  28272. 0, 2,
  28273. 1, 1,
  28274. 2, 2,
  28275. 3, 3,
  28276. 1, 3,
  28277. 2, 4 // 23: B + 12
  28278. ];
  28279. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28280. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28281. // First island of uv mapping
  28282. // v = 4h 3+ 2
  28283. // v = 3h 9+ 4
  28284. // v = 2h 9+ 5 B
  28285. // v = 1h 9 1 0
  28286. // v = 0h 3 8 7 A
  28287. // u = 0 1 2 3 4 5 6 *a
  28288. // Second island of uv mapping
  28289. // v = 4h 0+ B+ 4+
  28290. // v = 3h A+ 2+
  28291. // v = 2h 7+ 6 3+
  28292. // v = 1h 8+ 3+
  28293. // v = 0h
  28294. // u = 0 1 2 3 4 5 6 *a
  28295. // Face layout on texture UV mapping
  28296. // ============
  28297. // \ 4 /\ 16 / ======
  28298. // \ / \ / /\ 11 /
  28299. // \/ 7 \/ / \ /
  28300. // ======= / 10 \/
  28301. // /\ 17 /\ =======
  28302. // / \ / \ \ 15 /\
  28303. // / 8 \/ 12 \ \ / \
  28304. // ============ \/ 6 \
  28305. // \ 18 /\ ============
  28306. // \ / \ \ 5 /\ 0 /
  28307. // \/ 13 \ \ / \ /
  28308. // ======= \/ 1 \/
  28309. // =============
  28310. // /\ 19 /\ 2 /\
  28311. // / \ / \ / \
  28312. // / 14 \/ 9 \/ 3 \
  28313. // ===================
  28314. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28315. var ustep = 138 / 1024;
  28316. var vstep = 239 / 1024;
  28317. var uoffset = 60 / 1024;
  28318. var voffset = 26 / 1024;
  28319. // Second island should have margin, not to touch the first island
  28320. // avoid any borderline artefact in pixel rounding
  28321. var island_u_offset = -40 / 1024;
  28322. var island_v_offset = +20 / 1024;
  28323. // face is either island 0 or 1 :
  28324. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28325. var island = [
  28326. 0, 0, 0, 0, 1,
  28327. 0, 0, 1, 1, 0,
  28328. 0, 0, 1, 1, 0,
  28329. 0, 1, 1, 1, 0 // 15 - 19
  28330. ];
  28331. var indices = [];
  28332. var positions = [];
  28333. var normals = [];
  28334. var uvs = [];
  28335. var current_indice = 0;
  28336. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28337. var face_vertex_pos = new Array(3);
  28338. var face_vertex_uv = new Array(3);
  28339. var v012;
  28340. for (v012 = 0; v012 < 3; v012++) {
  28341. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28342. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28343. }
  28344. // create all with normals
  28345. for (var face = 0; face < 20; face++) {
  28346. // 3 vertex per face
  28347. for (v012 = 0; v012 < 3; v012++) {
  28348. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28349. var v_id = ico_indices[3 * face + v012];
  28350. // vertex have 3D position (x,y,z)
  28351. 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]);
  28352. // Normalize to get normal, then scale to radius
  28353. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28354. // uv Coordinates from vertex ID
  28355. 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);
  28356. }
  28357. // Subdivide the face (interpolate pos, norm, uv)
  28358. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28359. // - norm is linear interpolation of vertex corner normal
  28360. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28361. // - uv is linear interpolation
  28362. //
  28363. // Topology is as below for sub-divide by 2
  28364. // vertex shown as v0,v1,v2
  28365. // interp index is i1 to progress in range [v0,v1[
  28366. // interp index is i2 to progress in range [v0,v2[
  28367. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28368. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28369. //
  28370. //
  28371. // i2 v2
  28372. // ^ ^
  28373. // / / \
  28374. // / / \
  28375. // / / \
  28376. // / / (0,1) \
  28377. // / #---------\
  28378. // / / \ (0,0)'/ \
  28379. // / / \ / \
  28380. // / / \ / \
  28381. // / / (0,0) \ / (1,0) \
  28382. // / #---------#---------\
  28383. // v0 v1
  28384. //
  28385. // --------------------> i1
  28386. //
  28387. // interp of (i1,i2):
  28388. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28389. // along i1 : lerp(x0,x1, i1/(S-i2))
  28390. //
  28391. // centroid of triangle is needed to get help normal computation
  28392. // (c1,c2) are used for centroid location
  28393. var interp_vertex = function (i1, i2, c1, c2) {
  28394. // vertex is interpolated from
  28395. // - face_vertex_pos[0..2]
  28396. // - face_vertex_uv[0..2]
  28397. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28398. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28399. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28400. pos_interp.normalize();
  28401. var vertex_normal;
  28402. if (flat) {
  28403. // in flat mode, recalculate normal as face centroid normal
  28404. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28405. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28406. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28407. }
  28408. else {
  28409. // in smooth mode, recalculate normal from each single vertex position
  28410. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28411. }
  28412. // Vertex normal need correction due to X,Y,Z radius scaling
  28413. vertex_normal.x /= radiusX;
  28414. vertex_normal.y /= radiusY;
  28415. vertex_normal.z /= radiusZ;
  28416. vertex_normal.normalize();
  28417. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28418. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28419. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28420. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28421. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28422. uvs.push(uv_interp.x, uv_interp.y);
  28423. // push each vertex has member of a face
  28424. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28425. indices.push(current_indice);
  28426. current_indice++;
  28427. };
  28428. for (var i2 = 0; i2 < subdivisions; i2++) {
  28429. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28430. // face : (i1,i2) for /\ :
  28431. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28432. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28433. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28434. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28435. if (i1 + i2 + 1 < subdivisions) {
  28436. // face : (i1,i2)' for \/ :
  28437. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28438. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28439. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28440. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28441. }
  28442. }
  28443. }
  28444. }
  28445. // Sides
  28446. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28447. // Result
  28448. var vertexData = new VertexData();
  28449. vertexData.indices = indices;
  28450. vertexData.positions = positions;
  28451. vertexData.normals = normals;
  28452. vertexData.uvs = uvs;
  28453. return vertexData;
  28454. };
  28455. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28456. /**
  28457. * Creates the VertexData of the Polyhedron.
  28458. */
  28459. VertexData.CreatePolyhedron = function (options) {
  28460. // provided polyhedron types :
  28461. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28462. // 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)
  28463. var polyhedra = [];
  28464. 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]] };
  28465. 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]] };
  28466. polyhedra[2] = {
  28467. 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]],
  28468. 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]]
  28469. };
  28470. polyhedra[3] = {
  28471. 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]],
  28472. 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]]
  28473. };
  28474. polyhedra[4] = {
  28475. 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]],
  28476. 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]]
  28477. };
  28478. 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]] };
  28479. 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]] };
  28480. 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]] };
  28481. 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]] };
  28482. 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]] };
  28483. 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]] };
  28484. 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]] };
  28485. 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]] };
  28486. 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]] };
  28487. polyhedra[14] = {
  28488. 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]],
  28489. 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]]
  28490. };
  28491. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28492. var size = options.size;
  28493. var sizeX = options.sizeX || size || 1;
  28494. var sizeY = options.sizeY || size || 1;
  28495. var sizeZ = options.sizeZ || size || 1;
  28496. var data = options.custom || polyhedra[type];
  28497. var nbfaces = data.face.length;
  28498. var faceUV = options.faceUV || new Array(nbfaces);
  28499. var faceColors = options.faceColors;
  28500. var flat = (options.flat === undefined) ? true : options.flat;
  28501. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28502. var positions = [];
  28503. var indices = [];
  28504. var normals = [];
  28505. var uvs = [];
  28506. var colors = [];
  28507. var index = 0;
  28508. var faceIdx = 0; // face cursor in the array "indexes"
  28509. var indexes = [];
  28510. var i = 0;
  28511. var f = 0;
  28512. var u, v, ang, x, y, tmp;
  28513. // default face colors and UV if undefined
  28514. if (flat) {
  28515. for (f = 0; f < nbfaces; f++) {
  28516. if (faceColors && faceColors[f] === undefined) {
  28517. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28518. }
  28519. if (faceUV && faceUV[f] === undefined) {
  28520. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28521. }
  28522. }
  28523. }
  28524. if (!flat) {
  28525. for (i = 0; i < data.vertex.length; i++) {
  28526. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28527. uvs.push(0, 0);
  28528. }
  28529. for (f = 0; f < nbfaces; f++) {
  28530. for (i = 0; i < data.face[f].length - 2; i++) {
  28531. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28532. }
  28533. }
  28534. }
  28535. else {
  28536. for (f = 0; f < nbfaces; f++) {
  28537. var fl = data.face[f].length; // number of vertices of the current face
  28538. ang = 2 * Math.PI / fl;
  28539. x = 0.5 * Math.tan(ang / 2);
  28540. y = 0.5;
  28541. // positions, uvs, colors
  28542. for (i = 0; i < fl; i++) {
  28543. // positions
  28544. 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);
  28545. indexes.push(index);
  28546. index++;
  28547. // uvs
  28548. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28549. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28550. uvs.push(u, v);
  28551. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28552. y = x * Math.sin(ang) + y * Math.cos(ang);
  28553. x = tmp;
  28554. // colors
  28555. if (faceColors) {
  28556. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28557. }
  28558. }
  28559. // indices from indexes
  28560. for (i = 0; i < fl - 2; i++) {
  28561. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28562. }
  28563. faceIdx += fl;
  28564. }
  28565. }
  28566. VertexData.ComputeNormals(positions, indices, normals);
  28567. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28568. var vertexData = new VertexData();
  28569. vertexData.positions = positions;
  28570. vertexData.indices = indices;
  28571. vertexData.normals = normals;
  28572. vertexData.uvs = uvs;
  28573. if (faceColors && flat) {
  28574. vertexData.colors = colors;
  28575. }
  28576. return vertexData;
  28577. };
  28578. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28579. /**
  28580. * Creates the VertexData of the Torus Knot.
  28581. */
  28582. VertexData.CreateTorusKnot = function (options) {
  28583. var indices = [];
  28584. var positions = [];
  28585. var normals = [];
  28586. var uvs = [];
  28587. var radius = options.radius || 2;
  28588. var tube = options.tube || 0.5;
  28589. var radialSegments = options.radialSegments || 32;
  28590. var tubularSegments = options.tubularSegments || 32;
  28591. var p = options.p || 2;
  28592. var q = options.q || 3;
  28593. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28594. // Helper
  28595. var getPos = function (angle) {
  28596. var cu = Math.cos(angle);
  28597. var su = Math.sin(angle);
  28598. var quOverP = q / p * angle;
  28599. var cs = Math.cos(quOverP);
  28600. var tx = radius * (2 + cs) * 0.5 * cu;
  28601. var ty = radius * (2 + cs) * su * 0.5;
  28602. var tz = radius * Math.sin(quOverP) * 0.5;
  28603. return new BABYLON.Vector3(tx, ty, tz);
  28604. };
  28605. // Vertices
  28606. var i;
  28607. var j;
  28608. for (i = 0; i <= radialSegments; i++) {
  28609. var modI = i % radialSegments;
  28610. var u = modI / radialSegments * 2 * p * Math.PI;
  28611. var p1 = getPos(u);
  28612. var p2 = getPos(u + 0.01);
  28613. var tang = p2.subtract(p1);
  28614. var n = p2.add(p1);
  28615. var bitan = BABYLON.Vector3.Cross(tang, n);
  28616. n = BABYLON.Vector3.Cross(bitan, tang);
  28617. bitan.normalize();
  28618. n.normalize();
  28619. for (j = 0; j < tubularSegments; j++) {
  28620. var modJ = j % tubularSegments;
  28621. var v = modJ / tubularSegments * 2 * Math.PI;
  28622. var cx = -tube * Math.cos(v);
  28623. var cy = tube * Math.sin(v);
  28624. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28625. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28626. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28627. uvs.push(i / radialSegments);
  28628. uvs.push(j / tubularSegments);
  28629. }
  28630. }
  28631. for (i = 0; i < radialSegments; i++) {
  28632. for (j = 0; j < tubularSegments; j++) {
  28633. var jNext = (j + 1) % tubularSegments;
  28634. var a = i * tubularSegments + j;
  28635. var b = (i + 1) * tubularSegments + j;
  28636. var c = (i + 1) * tubularSegments + jNext;
  28637. var d = i * tubularSegments + jNext;
  28638. indices.push(d);
  28639. indices.push(b);
  28640. indices.push(a);
  28641. indices.push(d);
  28642. indices.push(c);
  28643. indices.push(b);
  28644. }
  28645. }
  28646. // Normals
  28647. VertexData.ComputeNormals(positions, indices, normals);
  28648. // Sides
  28649. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28650. // Result
  28651. var vertexData = new VertexData();
  28652. vertexData.indices = indices;
  28653. vertexData.positions = positions;
  28654. vertexData.normals = normals;
  28655. vertexData.uvs = uvs;
  28656. return vertexData;
  28657. };
  28658. // Tools
  28659. /**
  28660. * @param {any} - positions (number[] or Float32Array)
  28661. * @param {any} - indices (number[] or Uint16Array)
  28662. * @param {any} - normals (number[] or Float32Array)
  28663. * options (optional) :
  28664. * facetPositions : optional array of facet positions (vector3)
  28665. * facetNormals : optional array of facet normals (vector3)
  28666. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28667. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28668. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28669. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28670. * bInfo : optional bounding info, required for facetPartitioning computation
  28671. */
  28672. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28673. // temporary scalar variables
  28674. var index = 0; // facet index
  28675. var p1p2x = 0.0; // p1p2 vector x coordinate
  28676. var p1p2y = 0.0; // p1p2 vector y coordinate
  28677. var p1p2z = 0.0; // p1p2 vector z coordinate
  28678. var p3p2x = 0.0; // p3p2 vector x coordinate
  28679. var p3p2y = 0.0; // p3p2 vector y coordinate
  28680. var p3p2z = 0.0; // p3p2 vector z coordinate
  28681. var faceNormalx = 0.0; // facet normal x coordinate
  28682. var faceNormaly = 0.0; // facet normal y coordinate
  28683. var faceNormalz = 0.0; // facet normal z coordinate
  28684. var length = 0.0; // facet normal length before normalization
  28685. var v1x = 0; // vector1 x index in the positions array
  28686. var v1y = 0; // vector1 y index in the positions array
  28687. var v1z = 0; // vector1 z index in the positions array
  28688. var v2x = 0; // vector2 x index in the positions array
  28689. var v2y = 0; // vector2 y index in the positions array
  28690. var v2z = 0; // vector2 z index in the positions array
  28691. var v3x = 0; // vector3 x index in the positions array
  28692. var v3y = 0; // vector3 y index in the positions array
  28693. var v3z = 0; // vector3 z index in the positions array
  28694. var computeFacetNormals = false;
  28695. var computeFacetPositions = false;
  28696. var computeFacetPartitioning = false;
  28697. var faceNormalSign = 1;
  28698. if (options) {
  28699. computeFacetNormals = (options.facetNormals) ? true : false;
  28700. computeFacetPositions = (options.facetPositions) ? true : false;
  28701. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28702. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28703. }
  28704. // facetPartitioning reinit if needed
  28705. if (computeFacetPartitioning) {
  28706. var ox = 0; // X partitioning index for facet position
  28707. var oy = 0; // Y partinioning index for facet position
  28708. var oz = 0; // Z partinioning index for facet position
  28709. var b1x = 0; // X partitioning index for facet v1 vertex
  28710. var b1y = 0; // Y partitioning index for facet v1 vertex
  28711. var b1z = 0; // z partitioning index for facet v1 vertex
  28712. var b2x = 0; // X partitioning index for facet v2 vertex
  28713. var b2y = 0; // Y partitioning index for facet v2 vertex
  28714. var b2z = 0; // Z partitioning index for facet v2 vertex
  28715. var b3x = 0; // X partitioning index for facet v3 vertex
  28716. var b3y = 0; // Y partitioning index for facet v3 vertex
  28717. var b3z = 0; // Z partitioning index for facet v3 vertex
  28718. var block_idx_o = 0; // facet barycenter block index
  28719. var block_idx_v1 = 0; // v1 vertex block index
  28720. var block_idx_v2 = 0; // v2 vertex block index
  28721. var block_idx_v3 = 0; // v3 vertex block index
  28722. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28723. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28724. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28725. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28726. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28727. var subSq = options.subDiv.max * options.subDiv.max;
  28728. options.facetPartitioning.length = 0;
  28729. }
  28730. // reset the normals
  28731. for (index = 0; index < positions.length; index++) {
  28732. normals[index] = 0.0;
  28733. }
  28734. // Loop : 1 indice triplet = 1 facet
  28735. var nbFaces = indices.length / 3;
  28736. for (index = 0; index < nbFaces; index++) {
  28737. // get the indexes of the coordinates of each vertex of the facet
  28738. v1x = indices[index * 3] * 3;
  28739. v1y = v1x + 1;
  28740. v1z = v1x + 2;
  28741. v2x = indices[index * 3 + 1] * 3;
  28742. v2y = v2x + 1;
  28743. v2z = v2x + 2;
  28744. v3x = indices[index * 3 + 2] * 3;
  28745. v3y = v3x + 1;
  28746. v3z = v3x + 2;
  28747. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28748. p1p2y = positions[v1y] - positions[v2y];
  28749. p1p2z = positions[v1z] - positions[v2z];
  28750. p3p2x = positions[v3x] - positions[v2x];
  28751. p3p2y = positions[v3y] - positions[v2y];
  28752. p3p2z = positions[v3z] - positions[v2z];
  28753. // compute the face normal with the cross product
  28754. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28755. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28756. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28757. // normalize this normal and store it in the array facetData
  28758. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28759. length = (length === 0) ? 1.0 : length;
  28760. faceNormalx /= length;
  28761. faceNormaly /= length;
  28762. faceNormalz /= length;
  28763. if (computeFacetNormals) {
  28764. options.facetNormals[index].x = faceNormalx;
  28765. options.facetNormals[index].y = faceNormaly;
  28766. options.facetNormals[index].z = faceNormalz;
  28767. }
  28768. if (computeFacetPositions) {
  28769. // compute and the facet barycenter coordinates in the array facetPositions
  28770. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28771. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28772. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28773. }
  28774. if (computeFacetPartitioning) {
  28775. // store the facet indexes in arrays in the main facetPartitioning array :
  28776. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28777. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28778. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28779. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28780. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28781. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28782. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28783. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28784. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28785. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28786. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28787. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28788. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28789. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28790. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28791. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28792. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28793. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28794. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28795. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28796. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28797. // push each facet index in each block containing the vertex
  28798. options.facetPartitioning[block_idx_v1].push(index);
  28799. if (block_idx_v2 != block_idx_v1) {
  28800. options.facetPartitioning[block_idx_v2].push(index);
  28801. }
  28802. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28803. options.facetPartitioning[block_idx_v3].push(index);
  28804. }
  28805. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28806. options.facetPartitioning[block_idx_o].push(index);
  28807. }
  28808. }
  28809. // compute the normals anyway
  28810. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28811. normals[v1y] += faceNormaly;
  28812. normals[v1z] += faceNormalz;
  28813. normals[v2x] += faceNormalx;
  28814. normals[v2y] += faceNormaly;
  28815. normals[v2z] += faceNormalz;
  28816. normals[v3x] += faceNormalx;
  28817. normals[v3y] += faceNormaly;
  28818. normals[v3z] += faceNormalz;
  28819. }
  28820. // last normalization of each normal
  28821. for (index = 0; index < normals.length / 3; index++) {
  28822. faceNormalx = normals[index * 3];
  28823. faceNormaly = normals[index * 3 + 1];
  28824. faceNormalz = normals[index * 3 + 2];
  28825. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28826. length = (length === 0) ? 1.0 : length;
  28827. faceNormalx /= length;
  28828. faceNormaly /= length;
  28829. faceNormalz /= length;
  28830. normals[index * 3] = faceNormalx;
  28831. normals[index * 3 + 1] = faceNormaly;
  28832. normals[index * 3 + 2] = faceNormalz;
  28833. }
  28834. };
  28835. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28836. var li = indices.length;
  28837. var ln = normals.length;
  28838. var i;
  28839. var n;
  28840. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28841. switch (sideOrientation) {
  28842. case BABYLON.Mesh.FRONTSIDE:
  28843. // nothing changed
  28844. break;
  28845. case BABYLON.Mesh.BACKSIDE:
  28846. var tmp;
  28847. // indices
  28848. for (i = 0; i < li; i += 3) {
  28849. tmp = indices[i];
  28850. indices[i] = indices[i + 2];
  28851. indices[i + 2] = tmp;
  28852. }
  28853. // normals
  28854. for (n = 0; n < ln; n++) {
  28855. normals[n] = -normals[n];
  28856. }
  28857. break;
  28858. case BABYLON.Mesh.DOUBLESIDE:
  28859. // positions
  28860. var lp = positions.length;
  28861. var l = lp / 3;
  28862. for (var p = 0; p < lp; p++) {
  28863. positions[lp + p] = positions[p];
  28864. }
  28865. // indices
  28866. for (i = 0; i < li; i += 3) {
  28867. indices[i + li] = indices[i + 2] + l;
  28868. indices[i + 1 + li] = indices[i + 1] + l;
  28869. indices[i + 2 + li] = indices[i] + l;
  28870. }
  28871. // normals
  28872. for (n = 0; n < ln; n++) {
  28873. normals[ln + n] = -normals[n];
  28874. }
  28875. // uvs
  28876. var lu = uvs.length;
  28877. var u = 0;
  28878. for (u = 0; u < lu; u++) {
  28879. uvs[u + lu] = uvs[u];
  28880. }
  28881. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28882. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28883. u = 0;
  28884. for (i = 0; i < lu / 2; i++) {
  28885. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28886. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28887. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28888. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28889. u += 2;
  28890. }
  28891. break;
  28892. }
  28893. };
  28894. /**
  28895. * Creates a new VertexData from the imported parameters.
  28896. */
  28897. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28898. var vertexData = new VertexData();
  28899. // positions
  28900. var positions = parsedVertexData.positions;
  28901. if (positions) {
  28902. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28903. }
  28904. // normals
  28905. var normals = parsedVertexData.normals;
  28906. if (normals) {
  28907. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28908. }
  28909. // tangents
  28910. var tangents = parsedVertexData.tangents;
  28911. if (tangents) {
  28912. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28913. }
  28914. // uvs
  28915. var uvs = parsedVertexData.uvs;
  28916. if (uvs) {
  28917. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28918. }
  28919. // uv2s
  28920. var uv2s = parsedVertexData.uv2s;
  28921. if (uv2s) {
  28922. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28923. }
  28924. // uv3s
  28925. var uv3s = parsedVertexData.uv3s;
  28926. if (uv3s) {
  28927. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28928. }
  28929. // uv4s
  28930. var uv4s = parsedVertexData.uv4s;
  28931. if (uv4s) {
  28932. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28933. }
  28934. // uv5s
  28935. var uv5s = parsedVertexData.uv5s;
  28936. if (uv5s) {
  28937. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28938. }
  28939. // uv6s
  28940. var uv6s = parsedVertexData.uv6s;
  28941. if (uv6s) {
  28942. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28943. }
  28944. // colors
  28945. var colors = parsedVertexData.colors;
  28946. if (colors) {
  28947. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28948. }
  28949. // matricesIndices
  28950. var matricesIndices = parsedVertexData.matricesIndices;
  28951. if (matricesIndices) {
  28952. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28953. }
  28954. // matricesWeights
  28955. var matricesWeights = parsedVertexData.matricesWeights;
  28956. if (matricesWeights) {
  28957. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28958. }
  28959. // indices
  28960. var indices = parsedVertexData.indices;
  28961. if (indices) {
  28962. vertexData.indices = indices;
  28963. }
  28964. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28965. };
  28966. return VertexData;
  28967. }());
  28968. BABYLON.VertexData = VertexData;
  28969. })(BABYLON || (BABYLON = {}));
  28970. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28971. var BABYLON;
  28972. (function (BABYLON) {
  28973. var Geometry = (function () {
  28974. function Geometry(id, scene, vertexData, updatable, mesh) {
  28975. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28976. this._totalVertices = 0;
  28977. this._isDisposed = false;
  28978. this.id = id;
  28979. this._engine = scene.getEngine();
  28980. this._meshes = [];
  28981. this._scene = scene;
  28982. //Init vertex buffer cache
  28983. this._vertexBuffers = {};
  28984. this._indices = [];
  28985. this._updatable = updatable;
  28986. // vertexData
  28987. if (vertexData) {
  28988. this.setAllVerticesData(vertexData, updatable);
  28989. }
  28990. else {
  28991. this._totalVertices = 0;
  28992. this._indices = [];
  28993. }
  28994. if (this._engine.getCaps().vertexArrayObject) {
  28995. this._vertexArrayObjects = {};
  28996. }
  28997. // applyToMesh
  28998. if (mesh) {
  28999. if (mesh.getClassName() === "LinesMesh") {
  29000. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  29001. this.updateExtend();
  29002. }
  29003. this.applyToMesh(mesh);
  29004. mesh.computeWorldMatrix(true);
  29005. }
  29006. }
  29007. Object.defineProperty(Geometry.prototype, "boundingBias", {
  29008. /**
  29009. * 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
  29010. * @returns The Bias Vector
  29011. */
  29012. get: function () {
  29013. return this._boundingBias;
  29014. },
  29015. set: function (value) {
  29016. if (this._boundingBias && this._boundingBias.equals(value)) {
  29017. return;
  29018. }
  29019. this._boundingBias = value.clone();
  29020. this.updateBoundingInfo(true, null);
  29021. },
  29022. enumerable: true,
  29023. configurable: true
  29024. });
  29025. Object.defineProperty(Geometry.prototype, "extend", {
  29026. get: function () {
  29027. return this._extend;
  29028. },
  29029. enumerable: true,
  29030. configurable: true
  29031. });
  29032. Geometry.prototype.getScene = function () {
  29033. return this._scene;
  29034. };
  29035. Geometry.prototype.getEngine = function () {
  29036. return this._engine;
  29037. };
  29038. Geometry.prototype.isReady = function () {
  29039. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  29040. };
  29041. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  29042. get: function () {
  29043. for (var index = 0; index < this._meshes.length; index++) {
  29044. if (!this._meshes[index].doNotSerialize) {
  29045. return false;
  29046. }
  29047. }
  29048. return true;
  29049. },
  29050. enumerable: true,
  29051. configurable: true
  29052. });
  29053. Geometry.prototype._rebuild = function () {
  29054. if (this._vertexArrayObjects) {
  29055. this._vertexArrayObjects = {};
  29056. }
  29057. // Index buffer
  29058. if (this._meshes.length !== 0 && this._indices) {
  29059. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29060. }
  29061. // Vertex buffers
  29062. for (var key in this._vertexBuffers) {
  29063. var vertexBuffer = this._vertexBuffers[key];
  29064. vertexBuffer._rebuild();
  29065. }
  29066. };
  29067. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  29068. vertexData.applyToGeometry(this, updatable);
  29069. this.notifyUpdate();
  29070. };
  29071. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29072. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  29073. this.setVerticesBuffer(buffer);
  29074. };
  29075. Geometry.prototype.removeVerticesData = function (kind) {
  29076. if (this._vertexBuffers[kind]) {
  29077. this._vertexBuffers[kind].dispose();
  29078. delete this._vertexBuffers[kind];
  29079. }
  29080. };
  29081. Geometry.prototype.setVerticesBuffer = function (buffer) {
  29082. var kind = buffer.getKind();
  29083. if (this._vertexBuffers[kind]) {
  29084. this._vertexBuffers[kind].dispose();
  29085. }
  29086. this._vertexBuffers[kind] = buffer;
  29087. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29088. var data = buffer.getData();
  29089. var stride = buffer.getStrideSize();
  29090. this._totalVertices = data.length / stride;
  29091. this.updateExtend(data, stride);
  29092. this._resetPointsArrayCache();
  29093. var meshes = this._meshes;
  29094. var numOfMeshes = meshes.length;
  29095. for (var index = 0; index < numOfMeshes; index++) {
  29096. var mesh = meshes[index];
  29097. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29098. mesh._createGlobalSubMesh(false);
  29099. mesh.computeWorldMatrix(true);
  29100. }
  29101. }
  29102. this.notifyUpdate(kind);
  29103. if (this._vertexArrayObjects) {
  29104. this._disposeVertexArrayObjects();
  29105. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  29106. }
  29107. };
  29108. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  29109. var vertexBuffer = this.getVertexBuffer(kind);
  29110. if (!vertexBuffer) {
  29111. return;
  29112. }
  29113. vertexBuffer.updateDirectly(data, offset);
  29114. this.notifyUpdate(kind);
  29115. };
  29116. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  29117. var vertexBuffer = this.getVertexBuffer(kind);
  29118. if (!vertexBuffer) {
  29119. return;
  29120. }
  29121. vertexBuffer.update(data);
  29122. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29123. var stride = vertexBuffer.getStrideSize();
  29124. this._totalVertices = data.length / stride;
  29125. this.updateBoundingInfo(updateExtends, data);
  29126. }
  29127. this.notifyUpdate(kind);
  29128. };
  29129. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  29130. if (updateExtends) {
  29131. this.updateExtend(data);
  29132. }
  29133. var meshes = this._meshes;
  29134. var numOfMeshes = meshes.length;
  29135. this._resetPointsArrayCache();
  29136. for (var index = 0; index < numOfMeshes; index++) {
  29137. var mesh = meshes[index];
  29138. if (updateExtends) {
  29139. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29140. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29141. var subMesh = mesh.subMeshes[subIndex];
  29142. subMesh.refreshBoundingInfo();
  29143. }
  29144. }
  29145. }
  29146. };
  29147. Geometry.prototype._bind = function (effect, indexToBind) {
  29148. if (indexToBind === void 0) { indexToBind = undefined; }
  29149. if (indexToBind === undefined) {
  29150. indexToBind = this._indexBuffer;
  29151. }
  29152. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  29153. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  29154. return;
  29155. }
  29156. // Using VAO
  29157. if (!this._vertexArrayObjects[effect.key]) {
  29158. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  29159. }
  29160. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  29161. };
  29162. Geometry.prototype.getTotalVertices = function () {
  29163. if (!this.isReady()) {
  29164. return 0;
  29165. }
  29166. return this._totalVertices;
  29167. };
  29168. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  29169. var vertexBuffer = this.getVertexBuffer(kind);
  29170. if (!vertexBuffer) {
  29171. return null;
  29172. }
  29173. var orig = vertexBuffer.getData();
  29174. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  29175. return orig;
  29176. }
  29177. else {
  29178. var len = orig.length;
  29179. var copy = [];
  29180. for (var i = 0; i < len; i++) {
  29181. copy.push(orig[i]);
  29182. }
  29183. return copy;
  29184. }
  29185. };
  29186. Geometry.prototype.getVertexBuffer = function (kind) {
  29187. if (!this.isReady()) {
  29188. return null;
  29189. }
  29190. return this._vertexBuffers[kind];
  29191. };
  29192. Geometry.prototype.getVertexBuffers = function () {
  29193. if (!this.isReady()) {
  29194. return null;
  29195. }
  29196. return this._vertexBuffers;
  29197. };
  29198. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29199. if (!this._vertexBuffers) {
  29200. if (this._delayInfo) {
  29201. return this._delayInfo.indexOf(kind) !== -1;
  29202. }
  29203. return false;
  29204. }
  29205. return this._vertexBuffers[kind] !== undefined;
  29206. };
  29207. Geometry.prototype.getVerticesDataKinds = function () {
  29208. var result = [];
  29209. var kind;
  29210. if (!this._vertexBuffers && this._delayInfo) {
  29211. for (kind in this._delayInfo) {
  29212. result.push(kind);
  29213. }
  29214. }
  29215. else {
  29216. for (kind in this._vertexBuffers) {
  29217. result.push(kind);
  29218. }
  29219. }
  29220. return result;
  29221. };
  29222. Geometry.prototype.setIndices = function (indices, totalVertices) {
  29223. if (this._indexBuffer) {
  29224. this._engine._releaseBuffer(this._indexBuffer);
  29225. }
  29226. this._disposeVertexArrayObjects();
  29227. this._indices = indices;
  29228. if (this._meshes.length !== 0 && this._indices) {
  29229. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29230. }
  29231. if (totalVertices !== undefined) {
  29232. this._totalVertices = totalVertices;
  29233. }
  29234. var meshes = this._meshes;
  29235. var numOfMeshes = meshes.length;
  29236. for (var index = 0; index < numOfMeshes; index++) {
  29237. meshes[index]._createGlobalSubMesh(true);
  29238. }
  29239. this.notifyUpdate();
  29240. };
  29241. Geometry.prototype.getTotalIndices = function () {
  29242. if (!this.isReady()) {
  29243. return 0;
  29244. }
  29245. return this._indices.length;
  29246. };
  29247. Geometry.prototype.getIndices = function (copyWhenShared) {
  29248. if (!this.isReady()) {
  29249. return null;
  29250. }
  29251. var orig = this._indices;
  29252. if (!copyWhenShared || this._meshes.length === 1) {
  29253. return orig;
  29254. }
  29255. else {
  29256. var len = orig.length;
  29257. var copy = [];
  29258. for (var i = 0; i < len; i++) {
  29259. copy.push(orig[i]);
  29260. }
  29261. return copy;
  29262. }
  29263. };
  29264. Geometry.prototype.getIndexBuffer = function () {
  29265. if (!this.isReady()) {
  29266. return null;
  29267. }
  29268. return this._indexBuffer;
  29269. };
  29270. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  29271. if (!effect || !this._vertexArrayObjects) {
  29272. return;
  29273. }
  29274. if (this._vertexArrayObjects[effect.key]) {
  29275. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  29276. delete this._vertexArrayObjects[effect.key];
  29277. }
  29278. };
  29279. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29280. var meshes = this._meshes;
  29281. var index = meshes.indexOf(mesh);
  29282. if (index === -1) {
  29283. return;
  29284. }
  29285. meshes.splice(index, 1);
  29286. mesh._geometry = null;
  29287. if (meshes.length === 0 && shouldDispose) {
  29288. this.dispose();
  29289. }
  29290. };
  29291. Geometry.prototype.applyToMesh = function (mesh) {
  29292. if (mesh._geometry === this) {
  29293. return;
  29294. }
  29295. var previousGeometry = mesh._geometry;
  29296. if (previousGeometry) {
  29297. previousGeometry.releaseForMesh(mesh);
  29298. }
  29299. var meshes = this._meshes;
  29300. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29301. mesh._geometry = this;
  29302. this._scene.pushGeometry(this);
  29303. meshes.push(mesh);
  29304. if (this.isReady()) {
  29305. this._applyToMesh(mesh);
  29306. }
  29307. else {
  29308. mesh._boundingInfo = this._boundingInfo;
  29309. }
  29310. };
  29311. Geometry.prototype.updateExtend = function (data, stride) {
  29312. if (data === void 0) { data = null; }
  29313. if (!data) {
  29314. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  29315. }
  29316. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  29317. };
  29318. Geometry.prototype._applyToMesh = function (mesh) {
  29319. var numOfMeshes = this._meshes.length;
  29320. // vertexBuffers
  29321. for (var kind in this._vertexBuffers) {
  29322. if (numOfMeshes === 1) {
  29323. this._vertexBuffers[kind].create();
  29324. }
  29325. var buffer = this._vertexBuffers[kind].getBuffer();
  29326. if (buffer)
  29327. buffer.references = numOfMeshes;
  29328. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29329. if (!this._extend) {
  29330. this.updateExtend(this._vertexBuffers[kind].getData());
  29331. }
  29332. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29333. mesh._createGlobalSubMesh(false);
  29334. //bounding info was just created again, world matrix should be applied again.
  29335. mesh._updateBoundingInfo();
  29336. }
  29337. }
  29338. // indexBuffer
  29339. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  29340. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29341. }
  29342. if (this._indexBuffer) {
  29343. this._indexBuffer.references = numOfMeshes;
  29344. }
  29345. };
  29346. Geometry.prototype.notifyUpdate = function (kind) {
  29347. if (this.onGeometryUpdated) {
  29348. this.onGeometryUpdated(this, kind);
  29349. }
  29350. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  29351. var mesh = _a[_i];
  29352. mesh._markSubMeshesAsAttributesDirty();
  29353. }
  29354. };
  29355. Geometry.prototype.load = function (scene, onLoaded) {
  29356. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29357. return;
  29358. }
  29359. if (this.isReady()) {
  29360. if (onLoaded) {
  29361. onLoaded();
  29362. }
  29363. return;
  29364. }
  29365. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29366. this._queueLoad(scene, onLoaded);
  29367. };
  29368. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  29369. var _this = this;
  29370. scene._addPendingData(this);
  29371. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29372. _this._delayLoadingFunction(JSON.parse(data), _this);
  29373. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29374. _this._delayInfo = [];
  29375. scene._removePendingData(_this);
  29376. var meshes = _this._meshes;
  29377. var numOfMeshes = meshes.length;
  29378. for (var index = 0; index < numOfMeshes; index++) {
  29379. _this._applyToMesh(meshes[index]);
  29380. }
  29381. if (onLoaded) {
  29382. onLoaded();
  29383. }
  29384. }, function () { }, scene.database);
  29385. };
  29386. /**
  29387. * Invert the geometry to move from a right handed system to a left handed one.
  29388. */
  29389. Geometry.prototype.toLeftHanded = function () {
  29390. // Flip faces
  29391. var tIndices = this.getIndices(false);
  29392. if (tIndices != null && tIndices.length > 0) {
  29393. for (var i = 0; i < tIndices.length; i += 3) {
  29394. var tTemp = tIndices[i + 0];
  29395. tIndices[i + 0] = tIndices[i + 2];
  29396. tIndices[i + 2] = tTemp;
  29397. }
  29398. this.setIndices(tIndices);
  29399. }
  29400. // Negate position.z
  29401. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  29402. if (tPositions != null && tPositions.length > 0) {
  29403. for (var i = 0; i < tPositions.length; i += 3) {
  29404. tPositions[i + 2] = -tPositions[i + 2];
  29405. }
  29406. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  29407. }
  29408. // Negate normal.z
  29409. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  29410. if (tNormals != null && tNormals.length > 0) {
  29411. for (var i = 0; i < tNormals.length; i += 3) {
  29412. tNormals[i + 2] = -tNormals[i + 2];
  29413. }
  29414. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  29415. }
  29416. };
  29417. // Cache
  29418. Geometry.prototype._resetPointsArrayCache = function () {
  29419. this._positions = null;
  29420. };
  29421. Geometry.prototype._generatePointsArray = function () {
  29422. if (this._positions)
  29423. return true;
  29424. this._positions = [];
  29425. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29426. if (!data) {
  29427. return false;
  29428. }
  29429. for (var index = 0; index < data.length; index += 3) {
  29430. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  29431. }
  29432. return true;
  29433. };
  29434. Geometry.prototype.isDisposed = function () {
  29435. return this._isDisposed;
  29436. };
  29437. Geometry.prototype._disposeVertexArrayObjects = function () {
  29438. if (this._vertexArrayObjects) {
  29439. for (var kind in this._vertexArrayObjects) {
  29440. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  29441. }
  29442. this._vertexArrayObjects = {};
  29443. }
  29444. };
  29445. Geometry.prototype.dispose = function () {
  29446. var meshes = this._meshes;
  29447. var numOfMeshes = meshes.length;
  29448. var index;
  29449. for (index = 0; index < numOfMeshes; index++) {
  29450. this.releaseForMesh(meshes[index]);
  29451. }
  29452. this._meshes = [];
  29453. this._disposeVertexArrayObjects();
  29454. for (var kind in this._vertexBuffers) {
  29455. this._vertexBuffers[kind].dispose();
  29456. }
  29457. this._vertexBuffers = {};
  29458. this._totalVertices = 0;
  29459. if (this._indexBuffer) {
  29460. this._engine._releaseBuffer(this._indexBuffer);
  29461. }
  29462. this._indexBuffer = null;
  29463. this._indices = [];
  29464. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29465. this.delayLoadingFile = null;
  29466. this._delayLoadingFunction = null;
  29467. this._delayInfo = [];
  29468. this._boundingInfo = null;
  29469. this._scene.removeGeometry(this);
  29470. this._isDisposed = true;
  29471. };
  29472. Geometry.prototype.copy = function (id) {
  29473. var vertexData = new BABYLON.VertexData();
  29474. vertexData.indices = [];
  29475. var indices = this.getIndices();
  29476. for (var index = 0; index < indices.length; index++) {
  29477. vertexData.indices.push(indices[index]);
  29478. }
  29479. var updatable = false;
  29480. var stopChecking = false;
  29481. var kind;
  29482. for (kind in this._vertexBuffers) {
  29483. // using slice() to make a copy of the array and not just reference it
  29484. var data = this.getVerticesData(kind);
  29485. if (data instanceof Float32Array) {
  29486. vertexData.set(new Float32Array(data), kind);
  29487. }
  29488. else {
  29489. vertexData.set(data.slice(0), kind);
  29490. }
  29491. if (!stopChecking) {
  29492. updatable = this.getVertexBuffer(kind).isUpdatable();
  29493. stopChecking = !updatable;
  29494. }
  29495. }
  29496. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29497. geometry.delayLoadState = this.delayLoadState;
  29498. geometry.delayLoadingFile = this.delayLoadingFile;
  29499. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29500. for (kind in this._delayInfo) {
  29501. geometry._delayInfo = geometry._delayInfo || [];
  29502. geometry._delayInfo.push(kind);
  29503. }
  29504. // Bounding info
  29505. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29506. return geometry;
  29507. };
  29508. Geometry.prototype.serialize = function () {
  29509. var serializationObject = {};
  29510. serializationObject.id = this.id;
  29511. serializationObject.updatable = this._updatable;
  29512. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29513. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29514. }
  29515. return serializationObject;
  29516. };
  29517. Geometry.prototype.toNumberArray = function (origin) {
  29518. if (Array.isArray(origin)) {
  29519. return origin;
  29520. }
  29521. else {
  29522. return Array.prototype.slice.call(origin);
  29523. }
  29524. };
  29525. Geometry.prototype.serializeVerticeData = function () {
  29526. var serializationObject = this.serialize();
  29527. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29528. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  29529. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  29530. serializationObject.positions._updatable = true;
  29531. }
  29532. }
  29533. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29534. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29535. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29536. serializationObject.normals._updatable = true;
  29537. }
  29538. }
  29539. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29540. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29541. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29542. serializationObject.uvs._updatable = true;
  29543. }
  29544. }
  29545. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29546. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29547. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29548. serializationObject.uv2s._updatable = true;
  29549. }
  29550. }
  29551. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29552. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29553. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29554. serializationObject.uv3s._updatable = true;
  29555. }
  29556. }
  29557. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29558. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29559. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29560. serializationObject.uv4s._updatable = true;
  29561. }
  29562. }
  29563. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29564. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29565. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29566. serializationObject.uv5s._updatable = true;
  29567. }
  29568. }
  29569. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29570. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29571. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29572. serializationObject.uv6s._updatable = true;
  29573. }
  29574. }
  29575. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29576. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29577. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29578. serializationObject.colors._updatable = true;
  29579. }
  29580. }
  29581. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29582. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29583. serializationObject.matricesIndices._isExpanded = true;
  29584. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29585. serializationObject.matricesIndices._updatable = true;
  29586. }
  29587. }
  29588. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29589. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29590. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29591. serializationObject.matricesWeights._updatable = true;
  29592. }
  29593. }
  29594. serializationObject.indices = this.toNumberArray(this.getIndices());
  29595. return serializationObject;
  29596. };
  29597. // Statics
  29598. Geometry.ExtractFromMesh = function (mesh, id) {
  29599. var geometry = mesh._geometry;
  29600. if (!geometry) {
  29601. return null;
  29602. }
  29603. return geometry.copy(id);
  29604. };
  29605. /**
  29606. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29607. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29608. * Be aware Math.random() could cause collisions, but:
  29609. * "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"
  29610. */
  29611. Geometry.RandomId = function () {
  29612. return BABYLON.Tools.RandomId();
  29613. };
  29614. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29615. var scene = mesh.getScene();
  29616. // Geometry
  29617. var geometryId = parsedGeometry.geometryId;
  29618. if (geometryId) {
  29619. var geometry = scene.getGeometryByID(geometryId);
  29620. if (geometry) {
  29621. geometry.applyToMesh(mesh);
  29622. }
  29623. }
  29624. else if (parsedGeometry instanceof ArrayBuffer) {
  29625. var binaryInfo = mesh._binaryInfo;
  29626. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29627. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29628. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29629. }
  29630. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29631. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29632. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29633. }
  29634. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29635. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29636. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29637. }
  29638. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29639. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29640. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29641. }
  29642. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29643. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29644. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29645. }
  29646. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29647. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29648. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29649. }
  29650. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29651. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29652. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29653. }
  29654. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29655. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29656. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29657. }
  29658. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29659. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29660. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29661. }
  29662. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29663. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29664. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29665. }
  29666. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29667. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29668. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29669. }
  29670. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29671. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29672. mesh.setIndices(indicesData);
  29673. }
  29674. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29675. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29676. mesh.subMeshes = [];
  29677. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29678. var materialIndex = subMeshesData[(i * 5) + 0];
  29679. var verticesStart = subMeshesData[(i * 5) + 1];
  29680. var verticesCount = subMeshesData[(i * 5) + 2];
  29681. var indexStart = subMeshesData[(i * 5) + 3];
  29682. var indexCount = subMeshesData[(i * 5) + 4];
  29683. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29684. }
  29685. }
  29686. }
  29687. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29688. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29689. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29690. if (parsedGeometry.uvs) {
  29691. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29692. }
  29693. if (parsedGeometry.uvs2) {
  29694. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29695. }
  29696. if (parsedGeometry.uvs3) {
  29697. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29698. }
  29699. if (parsedGeometry.uvs4) {
  29700. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29701. }
  29702. if (parsedGeometry.uvs5) {
  29703. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29704. }
  29705. if (parsedGeometry.uvs6) {
  29706. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29707. }
  29708. if (parsedGeometry.colors) {
  29709. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29710. }
  29711. if (parsedGeometry.matricesIndices) {
  29712. if (!parsedGeometry.matricesIndices._isExpanded) {
  29713. var floatIndices = [];
  29714. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29715. var matricesIndex = parsedGeometry.matricesIndices[i];
  29716. floatIndices.push(matricesIndex & 0x000000FF);
  29717. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29718. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29719. floatIndices.push(matricesIndex >> 24);
  29720. }
  29721. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29722. }
  29723. else {
  29724. delete parsedGeometry.matricesIndices._isExpanded;
  29725. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29726. }
  29727. }
  29728. if (parsedGeometry.matricesIndicesExtra) {
  29729. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29730. var floatIndices = [];
  29731. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29732. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29733. floatIndices.push(matricesIndex & 0x000000FF);
  29734. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29735. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29736. floatIndices.push(matricesIndex >> 24);
  29737. }
  29738. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29739. }
  29740. else {
  29741. delete parsedGeometry.matricesIndices._isExpanded;
  29742. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29743. }
  29744. }
  29745. if (parsedGeometry.matricesWeights) {
  29746. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29747. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29748. }
  29749. if (parsedGeometry.matricesWeightsExtra) {
  29750. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29751. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29752. }
  29753. mesh.setIndices(parsedGeometry.indices);
  29754. }
  29755. // SubMeshes
  29756. if (parsedGeometry.subMeshes) {
  29757. mesh.subMeshes = [];
  29758. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29759. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29760. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29761. }
  29762. }
  29763. // Flat shading
  29764. if (mesh._shouldGenerateFlatShading) {
  29765. mesh.convertToFlatShadedMesh();
  29766. delete mesh._shouldGenerateFlatShading;
  29767. }
  29768. // Update
  29769. mesh.computeWorldMatrix(true);
  29770. // Octree
  29771. if (scene['_selectionOctree']) {
  29772. scene['_selectionOctree'].addMesh(mesh);
  29773. }
  29774. };
  29775. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29776. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29777. return;
  29778. }
  29779. var size = matricesWeights.length;
  29780. for (var i = 0; i < size; i += influencers) {
  29781. var weight = 0;
  29782. var biggerIndex = i;
  29783. var biggerWeight = 0;
  29784. for (var j = 0; j < influencers - 1; j++) {
  29785. weight += matricesWeights[i + j];
  29786. if (matricesWeights[i + j] > biggerWeight) {
  29787. biggerWeight = matricesWeights[i + j];
  29788. biggerIndex = i + j;
  29789. }
  29790. }
  29791. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29792. }
  29793. };
  29794. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29795. if (scene.getGeometryByID(parsedVertexData.id)) {
  29796. return null; // null since geometry could be something else than a box...
  29797. }
  29798. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29799. if (BABYLON.Tags) {
  29800. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29801. }
  29802. if (parsedVertexData.delayLoadingFile) {
  29803. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29804. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29805. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29806. geometry._delayInfo = [];
  29807. if (parsedVertexData.hasUVs) {
  29808. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29809. }
  29810. if (parsedVertexData.hasUVs2) {
  29811. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29812. }
  29813. if (parsedVertexData.hasUVs3) {
  29814. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29815. }
  29816. if (parsedVertexData.hasUVs4) {
  29817. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29818. }
  29819. if (parsedVertexData.hasUVs5) {
  29820. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29821. }
  29822. if (parsedVertexData.hasUVs6) {
  29823. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29824. }
  29825. if (parsedVertexData.hasColors) {
  29826. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29827. }
  29828. if (parsedVertexData.hasMatricesIndices) {
  29829. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29830. }
  29831. if (parsedVertexData.hasMatricesWeights) {
  29832. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29833. }
  29834. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29835. }
  29836. else {
  29837. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29838. }
  29839. scene.pushGeometry(geometry, true);
  29840. return geometry;
  29841. };
  29842. return Geometry;
  29843. }());
  29844. BABYLON.Geometry = Geometry;
  29845. /////// Primitives //////////////////////////////////////////////
  29846. (function (Geometry) {
  29847. var Primitives;
  29848. (function (Primitives) {
  29849. /// Abstract class
  29850. var _Primitive = (function (_super) {
  29851. __extends(_Primitive, _super);
  29852. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29853. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29854. _this._canBeRegenerated = _canBeRegenerated;
  29855. _this._beingRegenerated = true;
  29856. _this.regenerate();
  29857. _this._beingRegenerated = false;
  29858. return _this;
  29859. }
  29860. _Primitive.prototype.canBeRegenerated = function () {
  29861. return this._canBeRegenerated;
  29862. };
  29863. _Primitive.prototype.regenerate = function () {
  29864. if (!this._canBeRegenerated) {
  29865. return;
  29866. }
  29867. this._beingRegenerated = true;
  29868. this.setAllVerticesData(this._regenerateVertexData(), false);
  29869. this._beingRegenerated = false;
  29870. };
  29871. _Primitive.prototype.asNewGeometry = function (id) {
  29872. return _super.prototype.copy.call(this, id);
  29873. };
  29874. // overrides
  29875. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29876. if (!this._beingRegenerated) {
  29877. return;
  29878. }
  29879. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29880. };
  29881. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29882. if (!this._beingRegenerated) {
  29883. return;
  29884. }
  29885. _super.prototype.setVerticesData.call(this, kind, data, false);
  29886. };
  29887. // to override
  29888. // protected
  29889. _Primitive.prototype._regenerateVertexData = function () {
  29890. throw new Error("Abstract method");
  29891. };
  29892. _Primitive.prototype.copy = function (id) {
  29893. throw new Error("Must be overriden in sub-classes.");
  29894. };
  29895. _Primitive.prototype.serialize = function () {
  29896. var serializationObject = _super.prototype.serialize.call(this);
  29897. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29898. return serializationObject;
  29899. };
  29900. return _Primitive;
  29901. }(Geometry));
  29902. Primitives._Primitive = _Primitive;
  29903. var Ribbon = (function (_super) {
  29904. __extends(Ribbon, _super);
  29905. // Members
  29906. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29907. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29908. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29909. _this.pathArray = pathArray;
  29910. _this.closeArray = closeArray;
  29911. _this.closePath = closePath;
  29912. _this.offset = offset;
  29913. _this.side = side;
  29914. return _this;
  29915. }
  29916. Ribbon.prototype._regenerateVertexData = function () {
  29917. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29918. };
  29919. Ribbon.prototype.copy = function (id) {
  29920. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29921. };
  29922. return Ribbon;
  29923. }(_Primitive));
  29924. Primitives.Ribbon = Ribbon;
  29925. var Box = (function (_super) {
  29926. __extends(Box, _super);
  29927. // Members
  29928. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29929. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29930. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29931. _this.size = size;
  29932. _this.side = side;
  29933. return _this;
  29934. }
  29935. Box.prototype._regenerateVertexData = function () {
  29936. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29937. };
  29938. Box.prototype.copy = function (id) {
  29939. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29940. };
  29941. Box.prototype.serialize = function () {
  29942. var serializationObject = _super.prototype.serialize.call(this);
  29943. serializationObject.size = this.size;
  29944. return serializationObject;
  29945. };
  29946. Box.Parse = function (parsedBox, scene) {
  29947. if (scene.getGeometryByID(parsedBox.id)) {
  29948. return null; // null since geometry could be something else than a box...
  29949. }
  29950. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29951. if (BABYLON.Tags) {
  29952. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29953. }
  29954. scene.pushGeometry(box, true);
  29955. return box;
  29956. };
  29957. return Box;
  29958. }(_Primitive));
  29959. Primitives.Box = Box;
  29960. var Sphere = (function (_super) {
  29961. __extends(Sphere, _super);
  29962. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29963. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29964. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29965. _this.segments = segments;
  29966. _this.diameter = diameter;
  29967. _this.side = side;
  29968. return _this;
  29969. }
  29970. Sphere.prototype._regenerateVertexData = function () {
  29971. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29972. };
  29973. Sphere.prototype.copy = function (id) {
  29974. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29975. };
  29976. Sphere.prototype.serialize = function () {
  29977. var serializationObject = _super.prototype.serialize.call(this);
  29978. serializationObject.segments = this.segments;
  29979. serializationObject.diameter = this.diameter;
  29980. return serializationObject;
  29981. };
  29982. Sphere.Parse = function (parsedSphere, scene) {
  29983. if (scene.getGeometryByID(parsedSphere.id)) {
  29984. return null; // null since geometry could be something else than a sphere...
  29985. }
  29986. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29987. if (BABYLON.Tags) {
  29988. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29989. }
  29990. scene.pushGeometry(sphere, true);
  29991. return sphere;
  29992. };
  29993. return Sphere;
  29994. }(_Primitive));
  29995. Primitives.Sphere = Sphere;
  29996. var Disc = (function (_super) {
  29997. __extends(Disc, _super);
  29998. // Members
  29999. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  30000. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30001. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30002. _this.radius = radius;
  30003. _this.tessellation = tessellation;
  30004. _this.side = side;
  30005. return _this;
  30006. }
  30007. Disc.prototype._regenerateVertexData = function () {
  30008. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  30009. };
  30010. Disc.prototype.copy = function (id) {
  30011. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  30012. };
  30013. return Disc;
  30014. }(_Primitive));
  30015. Primitives.Disc = Disc;
  30016. var Cylinder = (function (_super) {
  30017. __extends(Cylinder, _super);
  30018. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  30019. if (subdivisions === void 0) { subdivisions = 1; }
  30020. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30021. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30022. _this.height = height;
  30023. _this.diameterTop = diameterTop;
  30024. _this.diameterBottom = diameterBottom;
  30025. _this.tessellation = tessellation;
  30026. _this.subdivisions = subdivisions;
  30027. _this.side = side;
  30028. return _this;
  30029. }
  30030. Cylinder.prototype._regenerateVertexData = function () {
  30031. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  30032. };
  30033. Cylinder.prototype.copy = function (id) {
  30034. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  30035. };
  30036. Cylinder.prototype.serialize = function () {
  30037. var serializationObject = _super.prototype.serialize.call(this);
  30038. serializationObject.height = this.height;
  30039. serializationObject.diameterTop = this.diameterTop;
  30040. serializationObject.diameterBottom = this.diameterBottom;
  30041. serializationObject.tessellation = this.tessellation;
  30042. return serializationObject;
  30043. };
  30044. Cylinder.Parse = function (parsedCylinder, scene) {
  30045. if (scene.getGeometryByID(parsedCylinder.id)) {
  30046. return null; // null since geometry could be something else than a cylinder...
  30047. }
  30048. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  30049. if (BABYLON.Tags) {
  30050. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  30051. }
  30052. scene.pushGeometry(cylinder, true);
  30053. return cylinder;
  30054. };
  30055. return Cylinder;
  30056. }(_Primitive));
  30057. Primitives.Cylinder = Cylinder;
  30058. var Torus = (function (_super) {
  30059. __extends(Torus, _super);
  30060. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  30061. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30062. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30063. _this.diameter = diameter;
  30064. _this.thickness = thickness;
  30065. _this.tessellation = tessellation;
  30066. _this.side = side;
  30067. return _this;
  30068. }
  30069. Torus.prototype._regenerateVertexData = function () {
  30070. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  30071. };
  30072. Torus.prototype.copy = function (id) {
  30073. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  30074. };
  30075. Torus.prototype.serialize = function () {
  30076. var serializationObject = _super.prototype.serialize.call(this);
  30077. serializationObject.diameter = this.diameter;
  30078. serializationObject.thickness = this.thickness;
  30079. serializationObject.tessellation = this.tessellation;
  30080. return serializationObject;
  30081. };
  30082. Torus.Parse = function (parsedTorus, scene) {
  30083. if (scene.getGeometryByID(parsedTorus.id)) {
  30084. return null; // null since geometry could be something else than a torus...
  30085. }
  30086. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  30087. if (BABYLON.Tags) {
  30088. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  30089. }
  30090. scene.pushGeometry(torus, true);
  30091. return torus;
  30092. };
  30093. return Torus;
  30094. }(_Primitive));
  30095. Primitives.Torus = Torus;
  30096. var Ground = (function (_super) {
  30097. __extends(Ground, _super);
  30098. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  30099. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30100. _this.width = width;
  30101. _this.height = height;
  30102. _this.subdivisions = subdivisions;
  30103. return _this;
  30104. }
  30105. Ground.prototype._regenerateVertexData = function () {
  30106. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  30107. };
  30108. Ground.prototype.copy = function (id) {
  30109. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  30110. };
  30111. Ground.prototype.serialize = function () {
  30112. var serializationObject = _super.prototype.serialize.call(this);
  30113. serializationObject.width = this.width;
  30114. serializationObject.height = this.height;
  30115. serializationObject.subdivisions = this.subdivisions;
  30116. return serializationObject;
  30117. };
  30118. Ground.Parse = function (parsedGround, scene) {
  30119. if (scene.getGeometryByID(parsedGround.id)) {
  30120. return null; // null since geometry could be something else than a ground...
  30121. }
  30122. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  30123. if (BABYLON.Tags) {
  30124. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  30125. }
  30126. scene.pushGeometry(ground, true);
  30127. return ground;
  30128. };
  30129. return Ground;
  30130. }(_Primitive));
  30131. Primitives.Ground = Ground;
  30132. var TiledGround = (function (_super) {
  30133. __extends(TiledGround, _super);
  30134. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  30135. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30136. _this.xmin = xmin;
  30137. _this.zmin = zmin;
  30138. _this.xmax = xmax;
  30139. _this.zmax = zmax;
  30140. _this.subdivisions = subdivisions;
  30141. _this.precision = precision;
  30142. return _this;
  30143. }
  30144. TiledGround.prototype._regenerateVertexData = function () {
  30145. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  30146. };
  30147. TiledGround.prototype.copy = function (id) {
  30148. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  30149. };
  30150. return TiledGround;
  30151. }(_Primitive));
  30152. Primitives.TiledGround = TiledGround;
  30153. var Plane = (function (_super) {
  30154. __extends(Plane, _super);
  30155. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  30156. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30157. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30158. _this.size = size;
  30159. _this.side = side;
  30160. return _this;
  30161. }
  30162. Plane.prototype._regenerateVertexData = function () {
  30163. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  30164. };
  30165. Plane.prototype.copy = function (id) {
  30166. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30167. };
  30168. Plane.prototype.serialize = function () {
  30169. var serializationObject = _super.prototype.serialize.call(this);
  30170. serializationObject.size = this.size;
  30171. return serializationObject;
  30172. };
  30173. Plane.Parse = function (parsedPlane, scene) {
  30174. if (scene.getGeometryByID(parsedPlane.id)) {
  30175. return null; // null since geometry could be something else than a ground...
  30176. }
  30177. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  30178. if (BABYLON.Tags) {
  30179. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  30180. }
  30181. scene.pushGeometry(plane, true);
  30182. return plane;
  30183. };
  30184. return Plane;
  30185. }(_Primitive));
  30186. Primitives.Plane = Plane;
  30187. var TorusKnot = (function (_super) {
  30188. __extends(TorusKnot, _super);
  30189. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  30190. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30191. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30192. _this.radius = radius;
  30193. _this.tube = tube;
  30194. _this.radialSegments = radialSegments;
  30195. _this.tubularSegments = tubularSegments;
  30196. _this.p = p;
  30197. _this.q = q;
  30198. _this.side = side;
  30199. return _this;
  30200. }
  30201. TorusKnot.prototype._regenerateVertexData = function () {
  30202. 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 });
  30203. };
  30204. TorusKnot.prototype.copy = function (id) {
  30205. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  30206. };
  30207. TorusKnot.prototype.serialize = function () {
  30208. var serializationObject = _super.prototype.serialize.call(this);
  30209. serializationObject.radius = this.radius;
  30210. serializationObject.tube = this.tube;
  30211. serializationObject.radialSegments = this.radialSegments;
  30212. serializationObject.tubularSegments = this.tubularSegments;
  30213. serializationObject.p = this.p;
  30214. serializationObject.q = this.q;
  30215. return serializationObject;
  30216. };
  30217. ;
  30218. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  30219. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  30220. return null; // null since geometry could be something else than a ground...
  30221. }
  30222. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  30223. if (BABYLON.Tags) {
  30224. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  30225. }
  30226. scene.pushGeometry(torusKnot, true);
  30227. return torusKnot;
  30228. };
  30229. return TorusKnot;
  30230. }(_Primitive));
  30231. Primitives.TorusKnot = TorusKnot;
  30232. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  30233. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  30234. })(BABYLON || (BABYLON = {}));
  30235. //# sourceMappingURL=babylon.geometry.js.map
  30236. var BABYLON;
  30237. (function (BABYLON) {
  30238. var PostProcessManager = (function () {
  30239. function PostProcessManager(scene) {
  30240. this._vertexBuffers = {};
  30241. this._scene = scene;
  30242. }
  30243. PostProcessManager.prototype._prepareBuffers = function () {
  30244. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30245. return;
  30246. }
  30247. // VBO
  30248. var vertices = [];
  30249. vertices.push(1, 1);
  30250. vertices.push(-1, 1);
  30251. vertices.push(-1, -1);
  30252. vertices.push(1, -1);
  30253. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  30254. this._buildIndexBuffer();
  30255. };
  30256. PostProcessManager.prototype._buildIndexBuffer = function () {
  30257. // Indices
  30258. var indices = [];
  30259. indices.push(0);
  30260. indices.push(1);
  30261. indices.push(2);
  30262. indices.push(0);
  30263. indices.push(2);
  30264. indices.push(3);
  30265. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  30266. };
  30267. PostProcessManager.prototype._rebuild = function () {
  30268. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30269. return;
  30270. }
  30271. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  30272. this._buildIndexBuffer();
  30273. };
  30274. // Methods
  30275. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  30276. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30277. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30278. return false;
  30279. }
  30280. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  30281. return true;
  30282. };
  30283. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  30284. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30285. var engine = this._scene.getEngine();
  30286. for (var index = 0; index < postProcesses.length; index++) {
  30287. if (index < postProcesses.length - 1) {
  30288. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30289. }
  30290. else {
  30291. if (targetTexture) {
  30292. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  30293. }
  30294. else {
  30295. engine.restoreDefaultFramebuffer();
  30296. }
  30297. }
  30298. var pp = postProcesses[index];
  30299. var effect = pp.apply();
  30300. if (effect) {
  30301. pp.onBeforeRenderObservable.notifyObservers(effect);
  30302. // VBOs
  30303. this._prepareBuffers();
  30304. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30305. // Draw order
  30306. engine.draw(true, 0, 6);
  30307. pp.onAfterRenderObservable.notifyObservers(effect);
  30308. }
  30309. }
  30310. // Restore depth buffer
  30311. engine.setDepthBuffer(true);
  30312. engine.setDepthWrite(true);
  30313. };
  30314. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  30315. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30316. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30317. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30318. return;
  30319. }
  30320. var engine = this._scene.getEngine();
  30321. for (var index = 0, len = postProcesses.length; index < len; index++) {
  30322. if (index < len - 1) {
  30323. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30324. }
  30325. else {
  30326. if (targetTexture) {
  30327. engine.bindFramebuffer(targetTexture, faceIndex, null, null, forceFullscreenViewport);
  30328. }
  30329. else {
  30330. engine.restoreDefaultFramebuffer();
  30331. }
  30332. }
  30333. if (doNotPresent) {
  30334. break;
  30335. }
  30336. var pp = postProcesses[index];
  30337. var effect = pp.apply();
  30338. if (effect) {
  30339. pp.onBeforeRenderObservable.notifyObservers(effect);
  30340. // VBOs
  30341. this._prepareBuffers();
  30342. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30343. // Draw order
  30344. engine.draw(true, 0, 6);
  30345. pp.onAfterRenderObservable.notifyObservers(effect);
  30346. }
  30347. }
  30348. // Restore states
  30349. engine.setDepthBuffer(true);
  30350. engine.setDepthWrite(true);
  30351. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30352. };
  30353. PostProcessManager.prototype.dispose = function () {
  30354. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30355. if (buffer) {
  30356. buffer.dispose();
  30357. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30358. }
  30359. if (this._indexBuffer) {
  30360. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30361. this._indexBuffer = null;
  30362. }
  30363. };
  30364. return PostProcessManager;
  30365. }());
  30366. BABYLON.PostProcessManager = PostProcessManager;
  30367. })(BABYLON || (BABYLON = {}));
  30368. //# sourceMappingURL=babylon.postProcessManager.js.map
  30369. var BABYLON;
  30370. (function (BABYLON) {
  30371. /**
  30372. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  30373. */
  30374. var PerformanceMonitor = (function () {
  30375. /**
  30376. * constructor
  30377. * @param frameSampleSize The number of samples required to saturate the sliding window
  30378. */
  30379. function PerformanceMonitor(frameSampleSize) {
  30380. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  30381. this._enabled = true;
  30382. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  30383. }
  30384. /**
  30385. * Samples current frame
  30386. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  30387. */
  30388. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  30389. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  30390. if (!this._enabled)
  30391. return;
  30392. if (this._lastFrameTimeMs != null) {
  30393. var dt = timeMs - this._lastFrameTimeMs;
  30394. this._rollingFrameTime.add(dt);
  30395. }
  30396. this._lastFrameTimeMs = timeMs;
  30397. };
  30398. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  30399. /**
  30400. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30401. * @return Average frame time in milliseconds
  30402. */
  30403. get: function () {
  30404. return this._rollingFrameTime.average;
  30405. },
  30406. enumerable: true,
  30407. configurable: true
  30408. });
  30409. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  30410. /**
  30411. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30412. * @return Frame time variance in milliseconds squared
  30413. */
  30414. get: function () {
  30415. return this._rollingFrameTime.variance;
  30416. },
  30417. enumerable: true,
  30418. configurable: true
  30419. });
  30420. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  30421. /**
  30422. * Returns the frame time of the most recent frame
  30423. * @return Frame time in milliseconds
  30424. */
  30425. get: function () {
  30426. return this._rollingFrameTime.history(0);
  30427. },
  30428. enumerable: true,
  30429. configurable: true
  30430. });
  30431. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  30432. /**
  30433. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  30434. * @return Framerate in frames per second
  30435. */
  30436. get: function () {
  30437. return 1000.0 / this._rollingFrameTime.average;
  30438. },
  30439. enumerable: true,
  30440. configurable: true
  30441. });
  30442. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  30443. /**
  30444. * Returns the average framerate in frames per second using the most recent frame time
  30445. * @return Framerate in frames per second
  30446. */
  30447. get: function () {
  30448. return 1000.0 / this._rollingFrameTime.history(0);
  30449. },
  30450. enumerable: true,
  30451. configurable: true
  30452. });
  30453. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  30454. /**
  30455. * Returns true if enough samples have been taken to completely fill the sliding window
  30456. * @return true if saturated
  30457. */
  30458. get: function () {
  30459. return this._rollingFrameTime.isSaturated();
  30460. },
  30461. enumerable: true,
  30462. configurable: true
  30463. });
  30464. /**
  30465. * Enables contributions to the sliding window sample set
  30466. */
  30467. PerformanceMonitor.prototype.enable = function () {
  30468. this._enabled = true;
  30469. };
  30470. /**
  30471. * Disables contributions to the sliding window sample set
  30472. * Samples will not be interpolated over the disabled period
  30473. */
  30474. PerformanceMonitor.prototype.disable = function () {
  30475. this._enabled = false;
  30476. //clear last sample to avoid interpolating over the disabled period when next enabled
  30477. this._lastFrameTimeMs = null;
  30478. this._lastChangeTimeMs = null;
  30479. };
  30480. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  30481. /**
  30482. * Returns true if sampling is enabled
  30483. * @return true if enabled
  30484. */
  30485. get: function () {
  30486. return this._enabled;
  30487. },
  30488. enumerable: true,
  30489. configurable: true
  30490. });
  30491. /**
  30492. * Resets performance monitor
  30493. */
  30494. PerformanceMonitor.prototype.reset = function () {
  30495. //clear last sample to avoid interpolating over the disabled period when next enabled
  30496. this._lastFrameTimeMs = null;
  30497. this._lastChangeTimeMs = null;
  30498. //wipe record
  30499. this._rollingFrameTime.reset();
  30500. };
  30501. return PerformanceMonitor;
  30502. }());
  30503. BABYLON.PerformanceMonitor = PerformanceMonitor;
  30504. /**
  30505. * RollingAverage
  30506. *
  30507. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  30508. */
  30509. var RollingAverage = (function () {
  30510. /**
  30511. * constructor
  30512. * @param length The number of samples required to saturate the sliding window
  30513. */
  30514. function RollingAverage(length) {
  30515. this._samples = new Array(length);
  30516. this.reset();
  30517. }
  30518. /**
  30519. * Adds a sample to the sample set
  30520. * @param v The sample value
  30521. */
  30522. RollingAverage.prototype.add = function (v) {
  30523. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  30524. var delta;
  30525. //we need to check if we've already wrapped round
  30526. if (this.isSaturated()) {
  30527. //remove bottom of stack from mean
  30528. var bottomValue = this._samples[this._pos];
  30529. delta = bottomValue - this.average;
  30530. this.average -= delta / (this._sampleCount - 1);
  30531. this._m2 -= delta * (bottomValue - this.average);
  30532. }
  30533. else {
  30534. this._sampleCount++;
  30535. }
  30536. //add new value to mean
  30537. delta = v - this.average;
  30538. this.average += delta / (this._sampleCount);
  30539. this._m2 += delta * (v - this.average);
  30540. //set the new variance
  30541. this.variance = this._m2 / (this._sampleCount - 1);
  30542. this._samples[this._pos] = v;
  30543. this._pos++;
  30544. this._pos %= this._samples.length; //positive wrap around
  30545. };
  30546. /**
  30547. * Returns previously added values or null if outside of history or outside the sliding window domain
  30548. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30549. * @return Value previously recorded with add() or null if outside of range
  30550. */
  30551. RollingAverage.prototype.history = function (i) {
  30552. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30553. return null;
  30554. }
  30555. var i0 = this._wrapPosition(this._pos - 1.0);
  30556. return this._samples[this._wrapPosition(i0 - i)];
  30557. };
  30558. /**
  30559. * Returns true if enough samples have been taken to completely fill the sliding window
  30560. * @return true if sample-set saturated
  30561. */
  30562. RollingAverage.prototype.isSaturated = function () {
  30563. return this._sampleCount >= this._samples.length;
  30564. };
  30565. /**
  30566. * Resets the rolling average (equivalent to 0 samples taken so far)
  30567. */
  30568. RollingAverage.prototype.reset = function () {
  30569. this.average = 0;
  30570. this.variance = 0;
  30571. this._sampleCount = 0;
  30572. this._pos = 0;
  30573. this._m2 = 0;
  30574. };
  30575. /**
  30576. * Wraps a value around the sample range boundaries
  30577. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30578. * @return Wrapped position in sample range
  30579. */
  30580. RollingAverage.prototype._wrapPosition = function (i) {
  30581. var max = this._samples.length;
  30582. return ((i % max) + max) % max;
  30583. };
  30584. return RollingAverage;
  30585. }());
  30586. BABYLON.RollingAverage = RollingAverage;
  30587. })(BABYLON || (BABYLON = {}));
  30588. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30589. var BABYLON;
  30590. (function (BABYLON) {
  30591. var StandardMaterialDefines = (function (_super) {
  30592. __extends(StandardMaterialDefines, _super);
  30593. function StandardMaterialDefines() {
  30594. var _this = _super.call(this) || this;
  30595. _this.MAINUV1 = false;
  30596. _this.MAINUV2 = false;
  30597. _this.DIFFUSE = false;
  30598. _this.DIFFUSEDIRECTUV = 0;
  30599. _this.AMBIENT = false;
  30600. _this.AMBIENTDIRECTUV = 0;
  30601. _this.OPACITY = false;
  30602. _this.OPACITYDIRECTUV = 0;
  30603. _this.OPACITYRGB = false;
  30604. _this.REFLECTION = false;
  30605. _this.EMISSIVE = false;
  30606. _this.EMISSIVEDIRECTUV = 0;
  30607. _this.SPECULAR = false;
  30608. _this.SPECULARDIRECTUV = 0;
  30609. _this.BUMP = false;
  30610. _this.BUMPDIRECTUV = 0;
  30611. _this.PARALLAX = false;
  30612. _this.PARALLAXOCCLUSION = false;
  30613. _this.SPECULAROVERALPHA = false;
  30614. _this.CLIPPLANE = false;
  30615. _this.ALPHATEST = false;
  30616. _this.DEPTHPREPASS = false;
  30617. _this.ALPHAFROMDIFFUSE = false;
  30618. _this.POINTSIZE = false;
  30619. _this.FOG = false;
  30620. _this.SPECULARTERM = false;
  30621. _this.DIFFUSEFRESNEL = false;
  30622. _this.OPACITYFRESNEL = false;
  30623. _this.REFLECTIONFRESNEL = false;
  30624. _this.REFRACTIONFRESNEL = false;
  30625. _this.EMISSIVEFRESNEL = false;
  30626. _this.FRESNEL = false;
  30627. _this.NORMAL = false;
  30628. _this.UV1 = false;
  30629. _this.UV2 = false;
  30630. _this.VERTEXCOLOR = false;
  30631. _this.VERTEXALPHA = false;
  30632. _this.NUM_BONE_INFLUENCERS = 0;
  30633. _this.BonesPerMesh = 0;
  30634. _this.INSTANCES = false;
  30635. _this.GLOSSINESS = false;
  30636. _this.ROUGHNESS = false;
  30637. _this.EMISSIVEASILLUMINATION = false;
  30638. _this.LINKEMISSIVEWITHDIFFUSE = false;
  30639. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  30640. _this.LIGHTMAP = false;
  30641. _this.LIGHTMAPDIRECTUV = 0;
  30642. _this.USELIGHTMAPASSHADOWMAP = false;
  30643. _this.REFLECTIONMAP_3D = false;
  30644. _this.REFLECTIONMAP_SPHERICAL = false;
  30645. _this.REFLECTIONMAP_PLANAR = false;
  30646. _this.REFLECTIONMAP_CUBIC = false;
  30647. _this.REFLECTIONMAP_PROJECTION = false;
  30648. _this.REFLECTIONMAP_SKYBOX = false;
  30649. _this.REFLECTIONMAP_EXPLICIT = false;
  30650. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30651. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30652. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30653. _this.INVERTCUBICMAP = false;
  30654. _this.LOGARITHMICDEPTH = false;
  30655. _this.REFRACTION = false;
  30656. _this.REFRACTIONMAP_3D = false;
  30657. _this.REFLECTIONOVERALPHA = false;
  30658. _this.TWOSIDEDLIGHTING = false;
  30659. _this.SHADOWFLOAT = false;
  30660. _this.MORPHTARGETS = false;
  30661. _this.MORPHTARGETS_NORMAL = false;
  30662. _this.MORPHTARGETS_TANGENT = false;
  30663. _this.NUM_MORPH_INFLUENCERS = 0;
  30664. _this.IMAGEPROCESSING = false;
  30665. _this.VIGNETTE = false;
  30666. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  30667. _this.VIGNETTEBLENDMODEOPAQUE = false;
  30668. _this.TONEMAPPING = false;
  30669. _this.CONTRAST = false;
  30670. _this.COLORCURVES = false;
  30671. _this.COLORGRADING = false;
  30672. _this.SAMPLER3DGREENDEPTH = false;
  30673. _this.SAMPLER3DBGRMAP = false;
  30674. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  30675. _this.EXPOSURE = false;
  30676. _this.rebuild();
  30677. return _this;
  30678. }
  30679. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  30680. var modes = [
  30681. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  30682. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  30683. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  30684. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  30685. ];
  30686. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  30687. var mode = modes_1[_i];
  30688. this[mode] = (mode === modeToEnable);
  30689. }
  30690. };
  30691. return StandardMaterialDefines;
  30692. }(BABYLON.MaterialDefines));
  30693. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  30694. var StandardMaterial = (function (_super) {
  30695. __extends(StandardMaterial, _super);
  30696. function StandardMaterial(name, scene) {
  30697. var _this = _super.call(this, name, scene) || this;
  30698. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30699. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  30700. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  30701. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30702. _this.specularPower = 64;
  30703. _this._useAlphaFromDiffuseTexture = false;
  30704. _this._useEmissiveAsIllumination = false;
  30705. _this._linkEmissiveWithDiffuse = false;
  30706. _this._useSpecularOverAlpha = false;
  30707. _this._useReflectionOverAlpha = false;
  30708. _this._disableLighting = false;
  30709. _this._useParallax = false;
  30710. _this._useParallaxOcclusion = false;
  30711. _this.parallaxScaleBias = 0.05;
  30712. _this._roughness = 0;
  30713. _this.indexOfRefraction = 0.98;
  30714. _this.invertRefractionY = true;
  30715. _this._useLightmapAsShadowmap = false;
  30716. _this._useReflectionFresnelFromSpecular = false;
  30717. _this._useGlossinessFromSpecularMapAlpha = false;
  30718. _this._maxSimultaneousLights = 4;
  30719. /**
  30720. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30721. */
  30722. _this._invertNormalMapX = false;
  30723. /**
  30724. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30725. */
  30726. _this._invertNormalMapY = false;
  30727. /**
  30728. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30729. */
  30730. _this._twoSidedLighting = false;
  30731. _this._renderTargets = new BABYLON.SmartArray(16);
  30732. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30733. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30734. // Setup the default processing configuration to the scene.
  30735. _this._attachImageProcessingConfiguration(null);
  30736. _this.getRenderTargetTextures = function () {
  30737. _this._renderTargets.reset();
  30738. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30739. _this._renderTargets.push(_this._reflectionTexture);
  30740. }
  30741. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30742. _this._renderTargets.push(_this._refractionTexture);
  30743. }
  30744. return _this._renderTargets;
  30745. };
  30746. return _this;
  30747. }
  30748. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  30749. /**
  30750. * Gets the image processing configuration used either in this material.
  30751. */
  30752. get: function () {
  30753. return this._imageProcessingConfiguration;
  30754. },
  30755. /**
  30756. * Sets the Default image processing configuration used either in the this material.
  30757. *
  30758. * If sets to null, the scene one is in use.
  30759. */
  30760. set: function (value) {
  30761. this._attachImageProcessingConfiguration(value);
  30762. // Ensure the effect will be rebuilt.
  30763. this._markAllSubMeshesAsTexturesDirty();
  30764. },
  30765. enumerable: true,
  30766. configurable: true
  30767. });
  30768. /**
  30769. * Attaches a new image processing configuration to the Standard Material.
  30770. * @param configuration
  30771. */
  30772. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  30773. var _this = this;
  30774. if (configuration === this._imageProcessingConfiguration) {
  30775. return;
  30776. }
  30777. // Detaches observer.
  30778. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30779. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30780. }
  30781. // Pick the scene configuration if needed.
  30782. if (!configuration) {
  30783. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  30784. }
  30785. else {
  30786. this._imageProcessingConfiguration = configuration;
  30787. }
  30788. // Attaches observer.
  30789. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  30790. _this._markAllSubMeshesAsImageProcessingDirty();
  30791. });
  30792. };
  30793. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  30794. /**
  30795. * Gets wether the color curves effect is enabled.
  30796. */
  30797. get: function () {
  30798. return this.imageProcessingConfiguration.colorCurvesEnabled;
  30799. },
  30800. /**
  30801. * Sets wether the color curves effect is enabled.
  30802. */
  30803. set: function (value) {
  30804. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  30805. },
  30806. enumerable: true,
  30807. configurable: true
  30808. });
  30809. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  30810. /**
  30811. * Gets wether the color grading effect is enabled.
  30812. */
  30813. get: function () {
  30814. return this.imageProcessingConfiguration.colorGradingEnabled;
  30815. },
  30816. /**
  30817. * Gets wether the color grading effect is enabled.
  30818. */
  30819. set: function (value) {
  30820. this.imageProcessingConfiguration.colorGradingEnabled = value;
  30821. },
  30822. enumerable: true,
  30823. configurable: true
  30824. });
  30825. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  30826. /**
  30827. * Gets wether tonemapping is enabled or not.
  30828. */
  30829. get: function () {
  30830. return this._imageProcessingConfiguration.toneMappingEnabled;
  30831. },
  30832. /**
  30833. * Sets wether tonemapping is enabled or not
  30834. */
  30835. set: function (value) {
  30836. this._imageProcessingConfiguration.toneMappingEnabled = value;
  30837. },
  30838. enumerable: true,
  30839. configurable: true
  30840. });
  30841. ;
  30842. ;
  30843. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  30844. /**
  30845. * The camera exposure used on this material.
  30846. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30847. * This corresponds to a photographic exposure.
  30848. */
  30849. get: function () {
  30850. return this._imageProcessingConfiguration.exposure;
  30851. },
  30852. /**
  30853. * The camera exposure used on this material.
  30854. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30855. * This corresponds to a photographic exposure.
  30856. */
  30857. set: function (value) {
  30858. this._imageProcessingConfiguration.exposure = value;
  30859. },
  30860. enumerable: true,
  30861. configurable: true
  30862. });
  30863. ;
  30864. ;
  30865. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  30866. /**
  30867. * Gets The camera contrast used on this material.
  30868. */
  30869. get: function () {
  30870. return this._imageProcessingConfiguration.contrast;
  30871. },
  30872. /**
  30873. * Sets The camera contrast used on this material.
  30874. */
  30875. set: function (value) {
  30876. this._imageProcessingConfiguration.contrast = value;
  30877. },
  30878. enumerable: true,
  30879. configurable: true
  30880. });
  30881. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  30882. /**
  30883. * Gets the Color Grading 2D Lookup Texture.
  30884. */
  30885. get: function () {
  30886. return this._imageProcessingConfiguration.colorGradingTexture;
  30887. },
  30888. /**
  30889. * Sets the Color Grading 2D Lookup Texture.
  30890. */
  30891. set: function (value) {
  30892. this._imageProcessingConfiguration.colorGradingTexture = value;
  30893. },
  30894. enumerable: true,
  30895. configurable: true
  30896. });
  30897. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  30898. /**
  30899. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30900. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30901. * 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;
  30902. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30903. */
  30904. get: function () {
  30905. return this._imageProcessingConfiguration.colorCurves;
  30906. },
  30907. /**
  30908. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30909. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30910. * 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;
  30911. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30912. */
  30913. set: function (value) {
  30914. this._imageProcessingConfiguration.colorCurves = value;
  30915. },
  30916. enumerable: true,
  30917. configurable: true
  30918. });
  30919. StandardMaterial.prototype.getClassName = function () {
  30920. return "StandardMaterial";
  30921. };
  30922. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30923. get: function () {
  30924. return this._useLogarithmicDepth;
  30925. },
  30926. set: function (value) {
  30927. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30928. this._markAllSubMeshesAsMiscDirty();
  30929. },
  30930. enumerable: true,
  30931. configurable: true
  30932. });
  30933. StandardMaterial.prototype.needAlphaBlending = function () {
  30934. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  30935. };
  30936. StandardMaterial.prototype.needAlphaTesting = function () {
  30937. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  30938. };
  30939. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  30940. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  30941. };
  30942. StandardMaterial.prototype.getAlphaTestTexture = function () {
  30943. return this._diffuseTexture;
  30944. };
  30945. /**
  30946. * Child classes can use it to update shaders
  30947. */
  30948. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30949. if (this.isFrozen) {
  30950. if (this._wasPreviouslyReady && subMesh.effect) {
  30951. return true;
  30952. }
  30953. }
  30954. if (!subMesh._materialDefines) {
  30955. subMesh._materialDefines = new StandardMaterialDefines();
  30956. }
  30957. var scene = this.getScene();
  30958. var defines = subMesh._materialDefines;
  30959. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  30960. if (defines._renderId === scene.getRenderId()) {
  30961. return true;
  30962. }
  30963. }
  30964. var engine = scene.getEngine();
  30965. // Lights
  30966. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  30967. // Textures
  30968. if (defines._areTexturesDirty) {
  30969. defines._needUVs = false;
  30970. defines.MAINUV1 = false;
  30971. defines.MAINUV2 = false;
  30972. if (scene.texturesEnabled) {
  30973. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30974. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  30975. return false;
  30976. }
  30977. else {
  30978. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  30979. }
  30980. }
  30981. else {
  30982. defines.DIFFUSE = false;
  30983. }
  30984. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30985. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  30986. return false;
  30987. }
  30988. else {
  30989. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  30990. }
  30991. }
  30992. else {
  30993. defines.AMBIENT = false;
  30994. }
  30995. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30996. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  30997. return false;
  30998. }
  30999. else {
  31000. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  31001. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  31002. }
  31003. }
  31004. else {
  31005. defines.OPACITY = false;
  31006. }
  31007. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31008. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  31009. return false;
  31010. }
  31011. else {
  31012. defines._needNormals = true;
  31013. defines.REFLECTION = true;
  31014. defines.ROUGHNESS = (this._roughness > 0);
  31015. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  31016. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  31017. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  31018. switch (this._reflectionTexture.coordinatesMode) {
  31019. case BABYLON.Texture.CUBIC_MODE:
  31020. case BABYLON.Texture.INVCUBIC_MODE:
  31021. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  31022. break;
  31023. case BABYLON.Texture.EXPLICIT_MODE:
  31024. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  31025. break;
  31026. case BABYLON.Texture.PLANAR_MODE:
  31027. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  31028. break;
  31029. case BABYLON.Texture.PROJECTION_MODE:
  31030. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  31031. break;
  31032. case BABYLON.Texture.SKYBOX_MODE:
  31033. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  31034. break;
  31035. case BABYLON.Texture.SPHERICAL_MODE:
  31036. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  31037. break;
  31038. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  31039. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  31040. break;
  31041. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  31042. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  31043. break;
  31044. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  31045. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  31046. break;
  31047. }
  31048. }
  31049. }
  31050. else {
  31051. defines.REFLECTION = false;
  31052. }
  31053. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31054. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  31055. return false;
  31056. }
  31057. else {
  31058. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  31059. }
  31060. }
  31061. else {
  31062. defines.EMISSIVE = false;
  31063. }
  31064. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31065. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  31066. return false;
  31067. }
  31068. else {
  31069. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  31070. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  31071. }
  31072. }
  31073. else {
  31074. defines.LIGHTMAP = false;
  31075. }
  31076. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31077. if (!this._specularTexture.isReadyOrNotBlocking()) {
  31078. return false;
  31079. }
  31080. else {
  31081. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  31082. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  31083. }
  31084. }
  31085. else {
  31086. defines.SPECULAR = false;
  31087. }
  31088. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  31089. // Bump texure can not be not blocking.
  31090. if (!this._bumpTexture.isReady()) {
  31091. return false;
  31092. }
  31093. else {
  31094. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  31095. defines.PARALLAX = this._useParallax;
  31096. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  31097. }
  31098. }
  31099. else {
  31100. defines.BUMP = false;
  31101. }
  31102. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31103. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  31104. return false;
  31105. }
  31106. else {
  31107. defines._needUVs = true;
  31108. defines.REFRACTION = true;
  31109. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  31110. }
  31111. }
  31112. else {
  31113. defines.REFRACTION = false;
  31114. }
  31115. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  31116. }
  31117. else {
  31118. defines.DIFFUSE = false;
  31119. defines.AMBIENT = false;
  31120. defines.OPACITY = false;
  31121. defines.REFLECTION = false;
  31122. defines.EMISSIVE = false;
  31123. defines.LIGHTMAP = false;
  31124. defines.BUMP = false;
  31125. defines.REFRACTION = false;
  31126. }
  31127. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  31128. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  31129. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  31130. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  31131. }
  31132. if (defines._areImageProcessingDirty) {
  31133. if (!this._imageProcessingConfiguration.isReady()) {
  31134. return false;
  31135. }
  31136. this._imageProcessingConfiguration.prepareDefines(defines);
  31137. }
  31138. if (defines._areFresnelDirty) {
  31139. if (StandardMaterial.FresnelEnabled) {
  31140. // Fresnel
  31141. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  31142. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  31143. this._reflectionFresnelParameters) {
  31144. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  31145. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  31146. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  31147. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  31148. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  31149. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  31150. defines._needNormals = true;
  31151. defines.FRESNEL = true;
  31152. }
  31153. }
  31154. else {
  31155. defines.FRESNEL = false;
  31156. }
  31157. }
  31158. // Misc.
  31159. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  31160. // Attribs
  31161. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  31162. // Values that need to be evaluated on every frame
  31163. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  31164. // Get correct effect
  31165. if (defines.isDirty) {
  31166. defines.markAsProcessed();
  31167. scene.resetCachedMaterial();
  31168. // Fallbacks
  31169. var fallbacks = new BABYLON.EffectFallbacks();
  31170. if (defines.REFLECTION) {
  31171. fallbacks.addFallback(0, "REFLECTION");
  31172. }
  31173. if (defines.SPECULAR) {
  31174. fallbacks.addFallback(0, "SPECULAR");
  31175. }
  31176. if (defines.BUMP) {
  31177. fallbacks.addFallback(0, "BUMP");
  31178. }
  31179. if (defines.PARALLAX) {
  31180. fallbacks.addFallback(1, "PARALLAX");
  31181. }
  31182. if (defines.PARALLAXOCCLUSION) {
  31183. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  31184. }
  31185. if (defines.SPECULAROVERALPHA) {
  31186. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  31187. }
  31188. if (defines.FOG) {
  31189. fallbacks.addFallback(1, "FOG");
  31190. }
  31191. if (defines.POINTSIZE) {
  31192. fallbacks.addFallback(0, "POINTSIZE");
  31193. }
  31194. if (defines.LOGARITHMICDEPTH) {
  31195. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  31196. }
  31197. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  31198. if (defines.SPECULARTERM) {
  31199. fallbacks.addFallback(0, "SPECULARTERM");
  31200. }
  31201. if (defines.DIFFUSEFRESNEL) {
  31202. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  31203. }
  31204. if (defines.OPACITYFRESNEL) {
  31205. fallbacks.addFallback(2, "OPACITYFRESNEL");
  31206. }
  31207. if (defines.REFLECTIONFRESNEL) {
  31208. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  31209. }
  31210. if (defines.EMISSIVEFRESNEL) {
  31211. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  31212. }
  31213. if (defines.FRESNEL) {
  31214. fallbacks.addFallback(4, "FRESNEL");
  31215. }
  31216. //Attributes
  31217. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31218. if (defines.NORMAL) {
  31219. attribs.push(BABYLON.VertexBuffer.NormalKind);
  31220. }
  31221. if (defines.UV1) {
  31222. attribs.push(BABYLON.VertexBuffer.UVKind);
  31223. }
  31224. if (defines.UV2) {
  31225. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31226. }
  31227. if (defines.VERTEXCOLOR) {
  31228. attribs.push(BABYLON.VertexBuffer.ColorKind);
  31229. }
  31230. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  31231. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  31232. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  31233. var shaderName = "default";
  31234. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  31235. "vFogInfos", "vFogColor", "pointSize",
  31236. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  31237. "mBones",
  31238. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  31239. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  31240. "logarithmicDepthConstant", "vTangentSpaceParams"
  31241. ];
  31242. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  31243. var uniformBuffers = ["Material", "Scene"];
  31244. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  31245. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  31246. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  31247. uniformsNames: uniforms,
  31248. uniformBuffersNames: uniformBuffers,
  31249. samplers: samplers,
  31250. defines: defines,
  31251. maxSimultaneousLights: this._maxSimultaneousLights
  31252. });
  31253. if (this.customShaderNameResolve) {
  31254. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  31255. }
  31256. var join = defines.toString();
  31257. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  31258. attributes: attribs,
  31259. uniformsNames: uniforms,
  31260. uniformBuffersNames: uniformBuffers,
  31261. samplers: samplers,
  31262. defines: join,
  31263. fallbacks: fallbacks,
  31264. onCompiled: this.onCompiled,
  31265. onError: this.onError,
  31266. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  31267. }, engine), defines);
  31268. this.buildUniformLayout();
  31269. }
  31270. if (!subMesh.effect.isReady()) {
  31271. return false;
  31272. }
  31273. defines._renderId = scene.getRenderId();
  31274. this._wasPreviouslyReady = true;
  31275. return true;
  31276. };
  31277. StandardMaterial.prototype.buildUniformLayout = function () {
  31278. // Order is important !
  31279. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  31280. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  31281. this._uniformBuffer.addUniform("opacityParts", 4);
  31282. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  31283. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  31284. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  31285. this._uniformBuffer.addUniform("refractionRightColor", 4);
  31286. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  31287. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  31288. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  31289. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  31290. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  31291. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  31292. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  31293. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  31294. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  31295. this._uniformBuffer.addUniform("vBumpInfos", 3);
  31296. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  31297. this._uniformBuffer.addUniform("ambientMatrix", 16);
  31298. this._uniformBuffer.addUniform("opacityMatrix", 16);
  31299. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  31300. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  31301. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  31302. this._uniformBuffer.addUniform("specularMatrix", 16);
  31303. this._uniformBuffer.addUniform("bumpMatrix", 16);
  31304. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  31305. this._uniformBuffer.addUniform("refractionMatrix", 16);
  31306. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  31307. this._uniformBuffer.addUniform("vSpecularColor", 4);
  31308. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  31309. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  31310. this._uniformBuffer.addUniform("pointSize", 1);
  31311. this._uniformBuffer.create();
  31312. };
  31313. StandardMaterial.prototype.unbind = function () {
  31314. if (this._activeEffect) {
  31315. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  31316. this._activeEffect.setTexture("reflection2DSampler", null);
  31317. }
  31318. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  31319. this._activeEffect.setTexture("refraction2DSampler", null);
  31320. }
  31321. }
  31322. _super.prototype.unbind.call(this);
  31323. };
  31324. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31325. var scene = this.getScene();
  31326. var defines = subMesh._materialDefines;
  31327. if (!defines) {
  31328. return;
  31329. }
  31330. var effect = subMesh.effect;
  31331. this._activeEffect = effect;
  31332. // Matrices
  31333. this.bindOnlyWorldMatrix(world);
  31334. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  31335. // Bones
  31336. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  31337. if (mustRebind) {
  31338. this._uniformBuffer.bindToEffect(effect, "Material");
  31339. this.bindViewProjection(effect);
  31340. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  31341. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  31342. // Fresnel
  31343. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  31344. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  31345. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  31346. }
  31347. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  31348. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  31349. }
  31350. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  31351. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  31352. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  31353. }
  31354. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  31355. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  31356. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  31357. }
  31358. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  31359. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  31360. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  31361. }
  31362. }
  31363. // Textures
  31364. if (scene.texturesEnabled) {
  31365. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31366. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  31367. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  31368. }
  31369. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31370. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  31371. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  31372. }
  31373. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31374. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  31375. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  31376. }
  31377. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31378. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  31379. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  31380. }
  31381. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31382. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  31383. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  31384. }
  31385. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31386. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  31387. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  31388. }
  31389. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31390. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  31391. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  31392. }
  31393. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31394. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  31395. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  31396. if (scene._mirroredCameraPosition) {
  31397. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this.invertNormalMapX ? 1.0 : -1.0, this.invertNormalMapY ? 1.0 : -1.0);
  31398. }
  31399. else {
  31400. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this.invertNormalMapX ? -1.0 : 1.0, this.invertNormalMapY ? -1.0 : 1.0);
  31401. }
  31402. }
  31403. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31404. var depth = 1.0;
  31405. if (!this._refractionTexture.isCube) {
  31406. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  31407. if (this._refractionTexture.depth) {
  31408. depth = this._refractionTexture.depth;
  31409. }
  31410. }
  31411. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  31412. }
  31413. }
  31414. // Point size
  31415. if (this.pointsCloud) {
  31416. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  31417. }
  31418. if (defines.SPECULARTERM) {
  31419. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  31420. }
  31421. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  31422. // Diffuse
  31423. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  31424. }
  31425. // Textures
  31426. if (scene.texturesEnabled) {
  31427. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31428. effect.setTexture("diffuseSampler", this._diffuseTexture);
  31429. }
  31430. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31431. effect.setTexture("ambientSampler", this._ambientTexture);
  31432. }
  31433. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31434. effect.setTexture("opacitySampler", this._opacityTexture);
  31435. }
  31436. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31437. if (this._reflectionTexture.isCube) {
  31438. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  31439. }
  31440. else {
  31441. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  31442. }
  31443. }
  31444. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31445. effect.setTexture("emissiveSampler", this._emissiveTexture);
  31446. }
  31447. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31448. effect.setTexture("lightmapSampler", this._lightmapTexture);
  31449. }
  31450. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31451. effect.setTexture("specularSampler", this._specularTexture);
  31452. }
  31453. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31454. effect.setTexture("bumpSampler", this._bumpTexture);
  31455. }
  31456. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31457. var depth = 1.0;
  31458. if (this._refractionTexture.isCube) {
  31459. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  31460. }
  31461. else {
  31462. effect.setTexture("refraction2DSampler", this._refractionTexture);
  31463. }
  31464. }
  31465. }
  31466. // Clip plane
  31467. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  31468. // Colors
  31469. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  31470. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  31471. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  31472. }
  31473. if (mustRebind || !this.isFrozen) {
  31474. // Lights
  31475. if (scene.lightsEnabled && !this._disableLighting) {
  31476. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  31477. }
  31478. // View
  31479. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  31480. this.bindView(effect);
  31481. }
  31482. // Fog
  31483. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  31484. // Morph targets
  31485. if (defines.NUM_MORPH_INFLUENCERS) {
  31486. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  31487. }
  31488. // Log. depth
  31489. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  31490. // image processing
  31491. this._imageProcessingConfiguration.bind(this._activeEffect);
  31492. }
  31493. this._uniformBuffer.update();
  31494. this._afterBind(mesh, this._activeEffect);
  31495. };
  31496. StandardMaterial.prototype.getAnimatables = function () {
  31497. var results = [];
  31498. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  31499. results.push(this._diffuseTexture);
  31500. }
  31501. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  31502. results.push(this._ambientTexture);
  31503. }
  31504. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  31505. results.push(this._opacityTexture);
  31506. }
  31507. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  31508. results.push(this._reflectionTexture);
  31509. }
  31510. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  31511. results.push(this._emissiveTexture);
  31512. }
  31513. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  31514. results.push(this._specularTexture);
  31515. }
  31516. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  31517. results.push(this._bumpTexture);
  31518. }
  31519. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  31520. results.push(this._lightmapTexture);
  31521. }
  31522. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  31523. results.push(this._refractionTexture);
  31524. }
  31525. return results;
  31526. };
  31527. StandardMaterial.prototype.getActiveTextures = function () {
  31528. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31529. if (this._diffuseTexture) {
  31530. activeTextures.push(this._diffuseTexture);
  31531. }
  31532. if (this._ambientTexture) {
  31533. activeTextures.push(this._ambientTexture);
  31534. }
  31535. if (this._opacityTexture) {
  31536. activeTextures.push(this._opacityTexture);
  31537. }
  31538. if (this._reflectionTexture) {
  31539. activeTextures.push(this._reflectionTexture);
  31540. }
  31541. if (this._emissiveTexture) {
  31542. activeTextures.push(this._emissiveTexture);
  31543. }
  31544. if (this._specularTexture) {
  31545. activeTextures.push(this._specularTexture);
  31546. }
  31547. if (this._bumpTexture) {
  31548. activeTextures.push(this._bumpTexture);
  31549. }
  31550. if (this._lightmapTexture) {
  31551. activeTextures.push(this._lightmapTexture);
  31552. }
  31553. if (this._refractionTexture) {
  31554. activeTextures.push(this._refractionTexture);
  31555. }
  31556. return activeTextures;
  31557. };
  31558. StandardMaterial.prototype.hasTexture = function (texture) {
  31559. if (_super.prototype.hasTexture.call(this, texture)) {
  31560. return true;
  31561. }
  31562. if (this._diffuseTexture === texture) {
  31563. return true;
  31564. }
  31565. if (this._ambientTexture === texture) {
  31566. return true;
  31567. }
  31568. if (this._opacityTexture === texture) {
  31569. return true;
  31570. }
  31571. if (this._reflectionTexture === texture) {
  31572. return true;
  31573. }
  31574. if (this._emissiveTexture === texture) {
  31575. return true;
  31576. }
  31577. if (this._specularTexture === texture) {
  31578. return true;
  31579. }
  31580. if (this._bumpTexture === texture) {
  31581. return true;
  31582. }
  31583. if (this._lightmapTexture === texture) {
  31584. return true;
  31585. }
  31586. if (this._refractionTexture === texture) {
  31587. return true;
  31588. }
  31589. return false;
  31590. };
  31591. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31592. if (forceDisposeTextures) {
  31593. if (this._diffuseTexture) {
  31594. this._diffuseTexture.dispose();
  31595. }
  31596. if (this._ambientTexture) {
  31597. this._ambientTexture.dispose();
  31598. }
  31599. if (this._opacityTexture) {
  31600. this._opacityTexture.dispose();
  31601. }
  31602. if (this._reflectionTexture) {
  31603. this._reflectionTexture.dispose();
  31604. }
  31605. if (this._emissiveTexture) {
  31606. this._emissiveTexture.dispose();
  31607. }
  31608. if (this._specularTexture) {
  31609. this._specularTexture.dispose();
  31610. }
  31611. if (this._bumpTexture) {
  31612. this._bumpTexture.dispose();
  31613. }
  31614. if (this._lightmapTexture) {
  31615. this._lightmapTexture.dispose();
  31616. }
  31617. if (this._refractionTexture) {
  31618. this._refractionTexture.dispose();
  31619. }
  31620. }
  31621. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31622. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31623. }
  31624. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  31625. };
  31626. StandardMaterial.prototype.clone = function (name) {
  31627. var _this = this;
  31628. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  31629. result.name = name;
  31630. result.id = name;
  31631. return result;
  31632. };
  31633. StandardMaterial.prototype.serialize = function () {
  31634. return BABYLON.SerializationHelper.Serialize(this);
  31635. };
  31636. // Statics
  31637. StandardMaterial.Parse = function (source, scene, rootUrl) {
  31638. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  31639. };
  31640. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  31641. get: function () {
  31642. return StandardMaterial._DiffuseTextureEnabled;
  31643. },
  31644. set: function (value) {
  31645. if (StandardMaterial._DiffuseTextureEnabled === value) {
  31646. return;
  31647. }
  31648. StandardMaterial._DiffuseTextureEnabled = value;
  31649. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31650. },
  31651. enumerable: true,
  31652. configurable: true
  31653. });
  31654. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  31655. get: function () {
  31656. return StandardMaterial._AmbientTextureEnabled;
  31657. },
  31658. set: function (value) {
  31659. if (StandardMaterial._AmbientTextureEnabled === value) {
  31660. return;
  31661. }
  31662. StandardMaterial._AmbientTextureEnabled = value;
  31663. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31664. },
  31665. enumerable: true,
  31666. configurable: true
  31667. });
  31668. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  31669. get: function () {
  31670. return StandardMaterial._OpacityTextureEnabled;
  31671. },
  31672. set: function (value) {
  31673. if (StandardMaterial._OpacityTextureEnabled === value) {
  31674. return;
  31675. }
  31676. StandardMaterial._OpacityTextureEnabled = value;
  31677. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31678. },
  31679. enumerable: true,
  31680. configurable: true
  31681. });
  31682. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  31683. get: function () {
  31684. return StandardMaterial._ReflectionTextureEnabled;
  31685. },
  31686. set: function (value) {
  31687. if (StandardMaterial._ReflectionTextureEnabled === value) {
  31688. return;
  31689. }
  31690. StandardMaterial._ReflectionTextureEnabled = value;
  31691. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31692. },
  31693. enumerable: true,
  31694. configurable: true
  31695. });
  31696. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  31697. get: function () {
  31698. return StandardMaterial._EmissiveTextureEnabled;
  31699. },
  31700. set: function (value) {
  31701. if (StandardMaterial._EmissiveTextureEnabled === value) {
  31702. return;
  31703. }
  31704. StandardMaterial._EmissiveTextureEnabled = value;
  31705. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31706. },
  31707. enumerable: true,
  31708. configurable: true
  31709. });
  31710. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  31711. get: function () {
  31712. return StandardMaterial._SpecularTextureEnabled;
  31713. },
  31714. set: function (value) {
  31715. if (StandardMaterial._SpecularTextureEnabled === value) {
  31716. return;
  31717. }
  31718. StandardMaterial._SpecularTextureEnabled = value;
  31719. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31720. },
  31721. enumerable: true,
  31722. configurable: true
  31723. });
  31724. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  31725. get: function () {
  31726. return StandardMaterial._BumpTextureEnabled;
  31727. },
  31728. set: function (value) {
  31729. if (StandardMaterial._BumpTextureEnabled === value) {
  31730. return;
  31731. }
  31732. StandardMaterial._BumpTextureEnabled = value;
  31733. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31734. },
  31735. enumerable: true,
  31736. configurable: true
  31737. });
  31738. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  31739. get: function () {
  31740. return StandardMaterial._LightmapTextureEnabled;
  31741. },
  31742. set: function (value) {
  31743. if (StandardMaterial._LightmapTextureEnabled === value) {
  31744. return;
  31745. }
  31746. StandardMaterial._LightmapTextureEnabled = value;
  31747. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31748. },
  31749. enumerable: true,
  31750. configurable: true
  31751. });
  31752. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  31753. get: function () {
  31754. return StandardMaterial._RefractionTextureEnabled;
  31755. },
  31756. set: function (value) {
  31757. if (StandardMaterial._RefractionTextureEnabled === value) {
  31758. return;
  31759. }
  31760. StandardMaterial._RefractionTextureEnabled = value;
  31761. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31762. },
  31763. enumerable: true,
  31764. configurable: true
  31765. });
  31766. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  31767. get: function () {
  31768. return StandardMaterial._ColorGradingTextureEnabled;
  31769. },
  31770. set: function (value) {
  31771. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  31772. return;
  31773. }
  31774. StandardMaterial._ColorGradingTextureEnabled = value;
  31775. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31776. },
  31777. enumerable: true,
  31778. configurable: true
  31779. });
  31780. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  31781. get: function () {
  31782. return StandardMaterial._FresnelEnabled;
  31783. },
  31784. set: function (value) {
  31785. if (StandardMaterial._FresnelEnabled === value) {
  31786. return;
  31787. }
  31788. StandardMaterial._FresnelEnabled = value;
  31789. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  31790. },
  31791. enumerable: true,
  31792. configurable: true
  31793. });
  31794. return StandardMaterial;
  31795. }(BABYLON.PushMaterial));
  31796. // Flags used to enable or disable a type of texture for all Standard Materials
  31797. StandardMaterial._DiffuseTextureEnabled = true;
  31798. StandardMaterial._AmbientTextureEnabled = true;
  31799. StandardMaterial._OpacityTextureEnabled = true;
  31800. StandardMaterial._ReflectionTextureEnabled = true;
  31801. StandardMaterial._EmissiveTextureEnabled = true;
  31802. StandardMaterial._SpecularTextureEnabled = true;
  31803. StandardMaterial._BumpTextureEnabled = true;
  31804. StandardMaterial._LightmapTextureEnabled = true;
  31805. StandardMaterial._RefractionTextureEnabled = true;
  31806. StandardMaterial._ColorGradingTextureEnabled = true;
  31807. StandardMaterial._FresnelEnabled = true;
  31808. __decorate([
  31809. BABYLON.serializeAsTexture("diffuseTexture")
  31810. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  31811. __decorate([
  31812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31813. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  31814. __decorate([
  31815. BABYLON.serializeAsTexture("ambientTexture")
  31816. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  31817. __decorate([
  31818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31819. ], StandardMaterial.prototype, "ambientTexture", void 0);
  31820. __decorate([
  31821. BABYLON.serializeAsTexture("opacityTexture")
  31822. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  31823. __decorate([
  31824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31825. ], StandardMaterial.prototype, "opacityTexture", void 0);
  31826. __decorate([
  31827. BABYLON.serializeAsTexture("reflectionTexture")
  31828. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  31829. __decorate([
  31830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31831. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  31832. __decorate([
  31833. BABYLON.serializeAsTexture("emissiveTexture")
  31834. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  31835. __decorate([
  31836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31837. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  31838. __decorate([
  31839. BABYLON.serializeAsTexture("specularTexture")
  31840. ], StandardMaterial.prototype, "_specularTexture", void 0);
  31841. __decorate([
  31842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31843. ], StandardMaterial.prototype, "specularTexture", void 0);
  31844. __decorate([
  31845. BABYLON.serializeAsTexture("bumpTexture")
  31846. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  31847. __decorate([
  31848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31849. ], StandardMaterial.prototype, "bumpTexture", void 0);
  31850. __decorate([
  31851. BABYLON.serializeAsTexture("lightmapTexture")
  31852. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  31853. __decorate([
  31854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31855. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  31856. __decorate([
  31857. BABYLON.serializeAsTexture("refractionTexture")
  31858. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  31859. __decorate([
  31860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31861. ], StandardMaterial.prototype, "refractionTexture", void 0);
  31862. __decorate([
  31863. BABYLON.serializeAsColor3("ambient")
  31864. ], StandardMaterial.prototype, "ambientColor", void 0);
  31865. __decorate([
  31866. BABYLON.serializeAsColor3("diffuse")
  31867. ], StandardMaterial.prototype, "diffuseColor", void 0);
  31868. __decorate([
  31869. BABYLON.serializeAsColor3("specular")
  31870. ], StandardMaterial.prototype, "specularColor", void 0);
  31871. __decorate([
  31872. BABYLON.serializeAsColor3("emissive")
  31873. ], StandardMaterial.prototype, "emissiveColor", void 0);
  31874. __decorate([
  31875. BABYLON.serialize()
  31876. ], StandardMaterial.prototype, "specularPower", void 0);
  31877. __decorate([
  31878. BABYLON.serialize("useAlphaFromDiffuseTexture")
  31879. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  31880. __decorate([
  31881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31882. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  31883. __decorate([
  31884. BABYLON.serialize("useEmissiveAsIllumination")
  31885. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  31886. __decorate([
  31887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31888. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  31889. __decorate([
  31890. BABYLON.serialize("linkEmissiveWithDiffuse")
  31891. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  31892. __decorate([
  31893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31894. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  31895. __decorate([
  31896. BABYLON.serialize("useSpecularOverAlpha")
  31897. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  31898. __decorate([
  31899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31900. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  31901. __decorate([
  31902. BABYLON.serialize("useReflectionOverAlpha")
  31903. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  31904. __decorate([
  31905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31906. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  31907. __decorate([
  31908. BABYLON.serialize("disableLighting")
  31909. ], StandardMaterial.prototype, "_disableLighting", void 0);
  31910. __decorate([
  31911. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31912. ], StandardMaterial.prototype, "disableLighting", void 0);
  31913. __decorate([
  31914. BABYLON.serialize("useParallax")
  31915. ], StandardMaterial.prototype, "_useParallax", void 0);
  31916. __decorate([
  31917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31918. ], StandardMaterial.prototype, "useParallax", void 0);
  31919. __decorate([
  31920. BABYLON.serialize("useParallaxOcclusion")
  31921. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  31922. __decorate([
  31923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31924. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  31925. __decorate([
  31926. BABYLON.serialize()
  31927. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  31928. __decorate([
  31929. BABYLON.serialize("roughness")
  31930. ], StandardMaterial.prototype, "_roughness", void 0);
  31931. __decorate([
  31932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31933. ], StandardMaterial.prototype, "roughness", void 0);
  31934. __decorate([
  31935. BABYLON.serialize()
  31936. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  31937. __decorate([
  31938. BABYLON.serialize()
  31939. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  31940. __decorate([
  31941. BABYLON.serialize("useLightmapAsShadowmap")
  31942. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  31943. __decorate([
  31944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31945. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31946. __decorate([
  31947. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  31948. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  31949. __decorate([
  31950. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31951. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  31952. __decorate([
  31953. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  31954. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  31955. __decorate([
  31956. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31957. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  31958. __decorate([
  31959. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  31960. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  31961. __decorate([
  31962. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31963. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  31964. __decorate([
  31965. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  31966. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  31967. __decorate([
  31968. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31969. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  31970. __decorate([
  31971. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  31972. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  31973. __decorate([
  31974. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31975. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  31976. __decorate([
  31977. BABYLON.serialize("useReflectionFresnelFromSpecular")
  31978. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  31979. __decorate([
  31980. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31981. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  31982. __decorate([
  31983. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  31984. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  31985. __decorate([
  31986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31987. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  31988. __decorate([
  31989. BABYLON.serialize("maxSimultaneousLights")
  31990. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  31991. __decorate([
  31992. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31993. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  31994. __decorate([
  31995. BABYLON.serialize("invertNormalMapX")
  31996. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  31997. __decorate([
  31998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31999. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  32000. __decorate([
  32001. BABYLON.serialize("invertNormalMapY")
  32002. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  32003. __decorate([
  32004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32005. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  32006. __decorate([
  32007. BABYLON.serialize("twoSidedLighting")
  32008. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  32009. __decorate([
  32010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32011. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  32012. __decorate([
  32013. BABYLON.serialize()
  32014. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  32015. BABYLON.StandardMaterial = StandardMaterial;
  32016. })(BABYLON || (BABYLON = {}));
  32017. //# sourceMappingURL=babylon.standardMaterial.js.map
  32018. var BABYLON;
  32019. (function (BABYLON) {
  32020. var PBRMaterialDefines = (function (_super) {
  32021. __extends(PBRMaterialDefines, _super);
  32022. function PBRMaterialDefines() {
  32023. var _this = _super.call(this) || this;
  32024. _this.PBR = true;
  32025. _this.MAINUV1 = false;
  32026. _this.MAINUV2 = false;
  32027. _this.UV1 = false;
  32028. _this.UV2 = false;
  32029. _this.ALBEDO = false;
  32030. _this.ALBEDODIRECTUV = 0;
  32031. _this.VERTEXCOLOR = false;
  32032. _this.AMBIENT = false;
  32033. _this.AMBIENTDIRECTUV = 0;
  32034. _this.AMBIENTINGRAYSCALE = false;
  32035. _this.OPACITY = false;
  32036. _this.VERTEXALPHA = false;
  32037. _this.OPACITYDIRECTUV = 0;
  32038. _this.OPACITYRGB = false;
  32039. _this.ALPHATEST = false;
  32040. _this.DEPTHPREPASS = false;
  32041. _this.ALPHABLEND = false;
  32042. _this.ALPHAFROMALBEDO = false;
  32043. _this.ALPHATESTVALUE = 0.5;
  32044. _this.SPECULAROVERALPHA = false;
  32045. _this.RADIANCEOVERALPHA = false;
  32046. _this.ALPHAFRESNEL = false;
  32047. _this.PREMULTIPLYALPHA = false;
  32048. _this.EMISSIVE = false;
  32049. _this.EMISSIVEDIRECTUV = 0;
  32050. _this.REFLECTIVITY = false;
  32051. _this.REFLECTIVITYDIRECTUV = 0;
  32052. _this.SPECULARTERM = false;
  32053. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  32054. _this.MICROSURFACEAUTOMATIC = false;
  32055. _this.LODBASEDMICROSFURACE = false;
  32056. _this.MICROSURFACEMAP = false;
  32057. _this.MICROSURFACEMAPDIRECTUV = 0;
  32058. _this.METALLICWORKFLOW = false;
  32059. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  32060. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  32061. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  32062. _this.AOSTOREINMETALMAPRED = false;
  32063. _this.ENVIRONMENTBRDF = false;
  32064. _this.NORMAL = false;
  32065. _this.TANGENT = false;
  32066. _this.BUMP = false;
  32067. _this.BUMPDIRECTUV = 0;
  32068. _this.PARALLAX = false;
  32069. _this.PARALLAXOCCLUSION = false;
  32070. _this.NORMALXYSCALE = true;
  32071. _this.LIGHTMAP = false;
  32072. _this.LIGHTMAPDIRECTUV = 0;
  32073. _this.USELIGHTMAPASSHADOWMAP = false;
  32074. _this.REFLECTION = false;
  32075. _this.REFLECTIONMAP_3D = false;
  32076. _this.REFLECTIONMAP_SPHERICAL = false;
  32077. _this.REFLECTIONMAP_PLANAR = false;
  32078. _this.REFLECTIONMAP_CUBIC = false;
  32079. _this.REFLECTIONMAP_PROJECTION = false;
  32080. _this.REFLECTIONMAP_SKYBOX = false;
  32081. _this.REFLECTIONMAP_EXPLICIT = false;
  32082. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  32083. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  32084. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  32085. _this.INVERTCUBICMAP = false;
  32086. _this.USESPHERICALFROMREFLECTIONMAP = false;
  32087. _this.USESPHERICALINFRAGMENT = false;
  32088. _this.REFLECTIONMAP_OPPOSITEZ = false;
  32089. _this.LODINREFLECTIONALPHA = false;
  32090. _this.GAMMAREFLECTION = false;
  32091. _this.REFRACTION = false;
  32092. _this.REFRACTIONMAP_3D = false;
  32093. _this.REFRACTIONMAP_OPPOSITEZ = false;
  32094. _this.LODINREFRACTIONALPHA = false;
  32095. _this.GAMMAREFRACTION = false;
  32096. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  32097. _this.INSTANCES = false;
  32098. _this.NUM_BONE_INFLUENCERS = 0;
  32099. _this.BonesPerMesh = 0;
  32100. _this.MORPHTARGETS = false;
  32101. _this.MORPHTARGETS_NORMAL = false;
  32102. _this.MORPHTARGETS_TANGENT = false;
  32103. _this.NUM_MORPH_INFLUENCERS = 0;
  32104. _this.IMAGEPROCESSING = false;
  32105. _this.VIGNETTE = false;
  32106. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  32107. _this.VIGNETTEBLENDMODEOPAQUE = false;
  32108. _this.TONEMAPPING = false;
  32109. _this.CONTRAST = false;
  32110. _this.COLORCURVES = false;
  32111. _this.COLORGRADING = false;
  32112. _this.SAMPLER3DGREENDEPTH = false;
  32113. _this.SAMPLER3DBGRMAP = false;
  32114. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  32115. _this.EXPOSURE = false;
  32116. _this.USEPHYSICALLIGHTFALLOFF = false;
  32117. _this.TWOSIDEDLIGHTING = false;
  32118. _this.SHADOWFLOAT = false;
  32119. _this.CLIPPLANE = false;
  32120. _this.POINTSIZE = false;
  32121. _this.FOG = false;
  32122. _this.LOGARITHMICDEPTH = false;
  32123. _this.FORCENORMALFORWARD = false;
  32124. _this.rebuild();
  32125. return _this;
  32126. }
  32127. PBRMaterialDefines.prototype.reset = function () {
  32128. _super.prototype.reset.call(this);
  32129. this.ALPHATESTVALUE = 0.5;
  32130. this.PBR = true;
  32131. };
  32132. return PBRMaterialDefines;
  32133. }(BABYLON.MaterialDefines));
  32134. /**
  32135. * The Physically based material base class of BJS.
  32136. *
  32137. * This offers the main features of a standard PBR material.
  32138. * For more information, please refer to the documentation :
  32139. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  32140. */
  32141. var PBRBaseMaterial = (function (_super) {
  32142. __extends(PBRBaseMaterial, _super);
  32143. /**
  32144. * Instantiates a new PBRMaterial instance.
  32145. *
  32146. * @param name The material name
  32147. * @param scene The scene the material will be use in.
  32148. */
  32149. function PBRBaseMaterial(name, scene) {
  32150. var _this = _super.call(this, name, scene) || this;
  32151. /**
  32152. * Intensity of the direct lights e.g. the four lights available in your scene.
  32153. * This impacts both the direct diffuse and specular highlights.
  32154. */
  32155. _this._directIntensity = 1.0;
  32156. /**
  32157. * Intensity of the emissive part of the material.
  32158. * This helps controlling the emissive effect without modifying the emissive color.
  32159. */
  32160. _this._emissiveIntensity = 1.0;
  32161. /**
  32162. * Intensity of the environment e.g. how much the environment will light the object
  32163. * either through harmonics for rough material or through the refelction for shiny ones.
  32164. */
  32165. _this._environmentIntensity = 1.0;
  32166. /**
  32167. * This is a special control allowing the reduction of the specular highlights coming from the
  32168. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  32169. */
  32170. _this._specularIntensity = 1.0;
  32171. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  32172. /**
  32173. * Debug Control allowing disabling the bump map on this material.
  32174. */
  32175. _this._disableBumpMap = false;
  32176. /**
  32177. * AKA Occlusion Texture Intensity in other nomenclature.
  32178. */
  32179. _this._ambientTextureStrength = 1.0;
  32180. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  32181. /**
  32182. * AKA Diffuse Color in other nomenclature.
  32183. */
  32184. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  32185. /**
  32186. * AKA Specular Color in other nomenclature.
  32187. */
  32188. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  32189. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  32190. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  32191. /**
  32192. * AKA Glossiness in other nomenclature.
  32193. */
  32194. _this._microSurface = 0.9;
  32195. /**
  32196. * source material index of refraction (IOR)' / 'destination material IOR.
  32197. */
  32198. _this._indexOfRefraction = 0.66;
  32199. /**
  32200. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  32201. */
  32202. _this._invertRefractionY = false;
  32203. /**
  32204. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  32205. * Materials half opaque for instance using refraction could benefit from this control.
  32206. */
  32207. _this._linkRefractionWithTransparency = false;
  32208. _this._useLightmapAsShadowmap = false;
  32209. /**
  32210. * Specifies that the alpha is coming form the albedo channel alpha channel.
  32211. */
  32212. _this._useAlphaFromAlbedoTexture = false;
  32213. /**
  32214. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  32215. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  32216. */
  32217. _this._useSpecularOverAlpha = true;
  32218. /**
  32219. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  32220. */
  32221. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  32222. /**
  32223. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  32224. */
  32225. _this._useRoughnessFromMetallicTextureAlpha = true;
  32226. /**
  32227. * Specifies if the metallic texture contains the roughness information in its green channel.
  32228. */
  32229. _this._useRoughnessFromMetallicTextureGreen = false;
  32230. /**
  32231. * Specifies if the metallic texture contains the metallness information in its blue channel.
  32232. */
  32233. _this._useMetallnessFromMetallicTextureBlue = false;
  32234. /**
  32235. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  32236. */
  32237. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  32238. /**
  32239. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  32240. */
  32241. _this._useAmbientInGrayScale = false;
  32242. /**
  32243. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  32244. * The material will try to infer what glossiness each pixel should be.
  32245. */
  32246. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  32247. /**
  32248. * BJS is using an harcoded light falloff based on a manually sets up range.
  32249. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  32250. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  32251. */
  32252. _this._usePhysicalLightFalloff = true;
  32253. /**
  32254. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  32255. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  32256. */
  32257. _this._useRadianceOverAlpha = true;
  32258. /**
  32259. * Allows using the bump map in parallax mode.
  32260. */
  32261. _this._useParallax = false;
  32262. /**
  32263. * Allows using the bump map in parallax occlusion mode.
  32264. */
  32265. _this._useParallaxOcclusion = false;
  32266. /**
  32267. * Controls the scale bias of the parallax mode.
  32268. */
  32269. _this._parallaxScaleBias = 0.05;
  32270. /**
  32271. * If sets to true, disables all the lights affecting the material.
  32272. */
  32273. _this._disableLighting = false;
  32274. /**
  32275. * Number of Simultaneous lights allowed on the material.
  32276. */
  32277. _this._maxSimultaneousLights = 4;
  32278. /**
  32279. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  32280. */
  32281. _this._invertNormalMapX = false;
  32282. /**
  32283. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  32284. */
  32285. _this._invertNormalMapY = false;
  32286. /**
  32287. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32288. */
  32289. _this._twoSidedLighting = false;
  32290. /**
  32291. * Defines the alpha limits in alpha test mode.
  32292. */
  32293. _this._alphaCutOff = 0.4;
  32294. /**
  32295. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  32296. */
  32297. _this._forceAlphaTest = false;
  32298. /**
  32299. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  32300. * in your scene composition.
  32301. */
  32302. _this._preMultiplyAlpha = false;
  32303. /**
  32304. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32305. * And/Or occlude the blended part.
  32306. */
  32307. _this._useAlphaFresnel = false;
  32308. /**
  32309. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  32310. * from cos thetav and roughness:
  32311. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  32312. */
  32313. _this._environmentBRDFTexture = null;
  32314. /**
  32315. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  32316. */
  32317. _this._forceIrradianceInFragment = false;
  32318. /**
  32319. * Force normal to face away from face.
  32320. * (Temporary internal fix to remove before 3.1)
  32321. */
  32322. _this._forceNormalForward = false;
  32323. _this._renderTargets = new BABYLON.SmartArray(16);
  32324. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  32325. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  32326. _this._tempColor = new BABYLON.Color3();
  32327. // Setup the default processing configuration to the scene.
  32328. _this._attachImageProcessingConfiguration(null);
  32329. _this.getRenderTargetTextures = function () {
  32330. _this._renderTargets.reset();
  32331. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  32332. _this._renderTargets.push(_this._reflectionTexture);
  32333. }
  32334. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  32335. _this._renderTargets.push(_this._refractionTexture);
  32336. }
  32337. return _this._renderTargets;
  32338. };
  32339. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  32340. return _this;
  32341. }
  32342. /**
  32343. * Attaches a new image processing configuration to the PBR Material.
  32344. * @param configuration
  32345. */
  32346. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  32347. var _this = this;
  32348. if (configuration === this._imageProcessingConfiguration) {
  32349. return;
  32350. }
  32351. // Detaches observer.
  32352. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32353. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32354. }
  32355. // Pick the scene configuration if needed.
  32356. if (!configuration) {
  32357. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  32358. }
  32359. else {
  32360. this._imageProcessingConfiguration = configuration;
  32361. }
  32362. // Attaches observer.
  32363. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  32364. _this._markAllSubMeshesAsImageProcessingDirty();
  32365. });
  32366. };
  32367. PBRBaseMaterial.prototype.getClassName = function () {
  32368. return "PBRBaseMaterial";
  32369. };
  32370. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  32371. get: function () {
  32372. return this._useLogarithmicDepth;
  32373. },
  32374. set: function (value) {
  32375. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  32376. },
  32377. enumerable: true,
  32378. configurable: true
  32379. });
  32380. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  32381. if (this._linkRefractionWithTransparency) {
  32382. return false;
  32383. }
  32384. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  32385. };
  32386. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  32387. if (this._forceAlphaTest) {
  32388. return true;
  32389. }
  32390. if (this._linkRefractionWithTransparency) {
  32391. return false;
  32392. }
  32393. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  32394. };
  32395. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  32396. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  32397. };
  32398. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  32399. return this._albedoTexture;
  32400. };
  32401. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  32402. if (this.isFrozen) {
  32403. if (this._wasPreviouslyReady) {
  32404. return true;
  32405. }
  32406. }
  32407. if (!subMesh._materialDefines) {
  32408. subMesh._materialDefines = new PBRMaterialDefines();
  32409. }
  32410. var scene = this.getScene();
  32411. var defines = subMesh._materialDefines;
  32412. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  32413. if (defines._renderId === scene.getRenderId()) {
  32414. return true;
  32415. }
  32416. }
  32417. var engine = scene.getEngine();
  32418. // Lights
  32419. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  32420. defines._needNormals = true;
  32421. // Textures
  32422. if (defines._areTexturesDirty) {
  32423. defines._needUVs = false;
  32424. if (scene.texturesEnabled) {
  32425. if (scene.getEngine().getCaps().textureLOD) {
  32426. defines.LODBASEDMICROSFURACE = true;
  32427. }
  32428. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32429. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  32430. return false;
  32431. }
  32432. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  32433. }
  32434. else {
  32435. defines.ALBEDO = false;
  32436. }
  32437. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32438. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  32439. return false;
  32440. }
  32441. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  32442. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  32443. }
  32444. else {
  32445. defines.AMBIENT = false;
  32446. }
  32447. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32448. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  32449. return false;
  32450. }
  32451. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  32452. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  32453. }
  32454. else {
  32455. defines.OPACITY = false;
  32456. }
  32457. var reflectionTexture = this._getReflectionTexture();
  32458. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32459. if (!reflectionTexture.isReadyOrNotBlocking()) {
  32460. return false;
  32461. }
  32462. defines.REFLECTION = true;
  32463. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  32464. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  32465. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32466. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  32467. defines.INVERTCUBICMAP = true;
  32468. }
  32469. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  32470. switch (reflectionTexture.coordinatesMode) {
  32471. case BABYLON.Texture.CUBIC_MODE:
  32472. case BABYLON.Texture.INVCUBIC_MODE:
  32473. defines.REFLECTIONMAP_CUBIC = true;
  32474. break;
  32475. case BABYLON.Texture.EXPLICIT_MODE:
  32476. defines.REFLECTIONMAP_EXPLICIT = true;
  32477. break;
  32478. case BABYLON.Texture.PLANAR_MODE:
  32479. defines.REFLECTIONMAP_PLANAR = true;
  32480. break;
  32481. case BABYLON.Texture.PROJECTION_MODE:
  32482. defines.REFLECTIONMAP_PROJECTION = true;
  32483. break;
  32484. case BABYLON.Texture.SKYBOX_MODE:
  32485. defines.REFLECTIONMAP_SKYBOX = true;
  32486. break;
  32487. case BABYLON.Texture.SPHERICAL_MODE:
  32488. defines.REFLECTIONMAP_SPHERICAL = true;
  32489. break;
  32490. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  32491. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  32492. break;
  32493. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  32494. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  32495. break;
  32496. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  32497. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  32498. break;
  32499. }
  32500. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  32501. if (reflectionTexture.sphericalPolynomial) {
  32502. defines.USESPHERICALFROMREFLECTIONMAP = true;
  32503. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  32504. defines.USESPHERICALINFRAGMENT = true;
  32505. }
  32506. }
  32507. }
  32508. }
  32509. else {
  32510. defines.REFLECTION = false;
  32511. defines.REFLECTIONMAP_3D = false;
  32512. defines.REFLECTIONMAP_SPHERICAL = false;
  32513. defines.REFLECTIONMAP_PLANAR = false;
  32514. defines.REFLECTIONMAP_CUBIC = false;
  32515. defines.REFLECTIONMAP_PROJECTION = false;
  32516. defines.REFLECTIONMAP_SKYBOX = false;
  32517. defines.REFLECTIONMAP_EXPLICIT = false;
  32518. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  32519. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  32520. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  32521. defines.INVERTCUBICMAP = false;
  32522. defines.USESPHERICALFROMREFLECTIONMAP = false;
  32523. defines.USESPHERICALINFRAGMENT = false;
  32524. defines.REFLECTIONMAP_OPPOSITEZ = false;
  32525. defines.LODINREFLECTIONALPHA = false;
  32526. defines.GAMMAREFLECTION = false;
  32527. }
  32528. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32529. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  32530. return false;
  32531. }
  32532. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  32533. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  32534. }
  32535. else {
  32536. defines.LIGHTMAP = false;
  32537. }
  32538. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32539. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  32540. return false;
  32541. }
  32542. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  32543. }
  32544. else {
  32545. defines.EMISSIVE = false;
  32546. }
  32547. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32548. if (this._metallicTexture) {
  32549. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  32550. return false;
  32551. }
  32552. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  32553. defines.METALLICWORKFLOW = true;
  32554. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  32555. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  32556. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  32557. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  32558. }
  32559. else if (this._reflectivityTexture) {
  32560. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  32561. return false;
  32562. }
  32563. defines.METALLICWORKFLOW = false;
  32564. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  32565. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  32566. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  32567. }
  32568. else {
  32569. defines.METALLICWORKFLOW = false;
  32570. defines.REFLECTIVITY = false;
  32571. }
  32572. if (this._microSurfaceTexture) {
  32573. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  32574. return false;
  32575. }
  32576. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  32577. }
  32578. else {
  32579. defines.MICROSURFACEMAP = false;
  32580. }
  32581. }
  32582. else {
  32583. defines.REFLECTIVITY = false;
  32584. defines.MICROSURFACEMAP = false;
  32585. }
  32586. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32587. // Bump texure can not be none blocking.
  32588. if (!this._bumpTexture.isReady()) {
  32589. return false;
  32590. }
  32591. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  32592. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32593. defines.PARALLAX = true;
  32594. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  32595. }
  32596. else {
  32597. defines.PARALLAX = false;
  32598. }
  32599. }
  32600. else {
  32601. defines.BUMP = false;
  32602. }
  32603. var refractionTexture = this._getRefractionTexture();
  32604. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32605. if (!refractionTexture.isReadyOrNotBlocking()) {
  32606. return false;
  32607. }
  32608. defines.REFRACTION = true;
  32609. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  32610. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  32611. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  32612. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32613. if (this._linkRefractionWithTransparency) {
  32614. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  32615. }
  32616. }
  32617. else {
  32618. defines.REFRACTION = false;
  32619. }
  32620. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32621. // This is blocking.
  32622. if (!this._environmentBRDFTexture.isReady()) {
  32623. return false;
  32624. }
  32625. defines.ENVIRONMENTBRDF = true;
  32626. }
  32627. if (this._shouldUseAlphaFromAlbedoTexture()) {
  32628. defines.ALPHAFROMALBEDO = true;
  32629. }
  32630. }
  32631. if (this._useSpecularOverAlpha) {
  32632. defines.SPECULAROVERALPHA = true;
  32633. }
  32634. if (this._usePhysicalLightFalloff) {
  32635. defines.USEPHYSICALLIGHTFALLOFF = true;
  32636. }
  32637. if (this._useRadianceOverAlpha) {
  32638. defines.RADIANCEOVERALPHA = true;
  32639. }
  32640. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  32641. defines.METALLICWORKFLOW = true;
  32642. }
  32643. if (!this.backFaceCulling && this._twoSidedLighting) {
  32644. defines.TWOSIDEDLIGHTING = true;
  32645. }
  32646. defines.ALPHATESTVALUE = this._alphaCutOff;
  32647. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  32648. defines.ALPHABLEND = this.needAlphaBlending();
  32649. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  32650. }
  32651. if (defines._areImageProcessingDirty) {
  32652. if (!this._imageProcessingConfiguration.isReady()) {
  32653. return false;
  32654. }
  32655. this._imageProcessingConfiguration.prepareDefines(defines);
  32656. }
  32657. defines.FORCENORMALFORWARD = this._forceNormalForward;
  32658. // Misc.
  32659. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  32660. // Values that need to be evaluated on every frame
  32661. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  32662. // Attribs
  32663. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  32664. if (mesh) {
  32665. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32666. mesh.createNormals(true);
  32667. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  32668. }
  32669. }
  32670. }
  32671. // Get correct effect
  32672. if (defines.isDirty) {
  32673. defines.markAsProcessed();
  32674. scene.resetCachedMaterial();
  32675. // Fallbacks
  32676. var fallbacks = new BABYLON.EffectFallbacks();
  32677. if (defines.ENVIRONMENTBRDF) {
  32678. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  32679. }
  32680. if (defines.REFLECTION) {
  32681. fallbacks.addFallback(0, "REFLECTION");
  32682. }
  32683. if (defines.REFRACTION) {
  32684. fallbacks.addFallback(0, "REFRACTION");
  32685. }
  32686. if (defines.REFLECTIVITY) {
  32687. fallbacks.addFallback(0, "REFLECTIVITY");
  32688. }
  32689. if (defines.BUMP) {
  32690. fallbacks.addFallback(0, "BUMP");
  32691. }
  32692. if (defines.PARALLAX) {
  32693. fallbacks.addFallback(1, "PARALLAX");
  32694. }
  32695. if (defines.PARALLAXOCCLUSION) {
  32696. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  32697. }
  32698. if (defines.SPECULAROVERALPHA) {
  32699. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  32700. }
  32701. if (defines.FOG) {
  32702. fallbacks.addFallback(1, "FOG");
  32703. }
  32704. if (defines.POINTSIZE) {
  32705. fallbacks.addFallback(0, "POINTSIZE");
  32706. }
  32707. if (defines.LOGARITHMICDEPTH) {
  32708. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  32709. }
  32710. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  32711. if (defines.SPECULARTERM) {
  32712. fallbacks.addFallback(0, "SPECULARTERM");
  32713. }
  32714. if (defines.NUM_BONE_INFLUENCERS > 0) {
  32715. fallbacks.addCPUSkinningFallback(0, mesh);
  32716. }
  32717. //Attributes
  32718. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32719. if (defines.NORMAL) {
  32720. attribs.push(BABYLON.VertexBuffer.NormalKind);
  32721. }
  32722. if (defines.TANGENT) {
  32723. attribs.push(BABYLON.VertexBuffer.TangentKind);
  32724. }
  32725. if (defines.UV1) {
  32726. attribs.push(BABYLON.VertexBuffer.UVKind);
  32727. }
  32728. if (defines.UV2) {
  32729. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32730. }
  32731. if (defines.VERTEXCOLOR) {
  32732. attribs.push(BABYLON.VertexBuffer.ColorKind);
  32733. }
  32734. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  32735. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  32736. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  32737. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  32738. "vFogInfos", "vFogColor", "pointSize",
  32739. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  32740. "mBones",
  32741. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  32742. "vLightingIntensity",
  32743. "logarithmicDepthConstant",
  32744. "vSphericalX", "vSphericalY", "vSphericalZ",
  32745. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  32746. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  32747. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  32748. "vTangentSpaceParams"
  32749. ];
  32750. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  32751. "bumpSampler", "lightmapSampler", "opacitySampler",
  32752. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  32753. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  32754. "microSurfaceSampler", "environmentBrdfSampler"];
  32755. var uniformBuffers = ["Material", "Scene"];
  32756. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  32757. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  32758. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  32759. uniformsNames: uniforms,
  32760. uniformBuffersNames: uniformBuffers,
  32761. samplers: samplers,
  32762. defines: defines,
  32763. maxSimultaneousLights: this._maxSimultaneousLights
  32764. });
  32765. var onCompiled = function (effect) {
  32766. if (this.onCompiled) {
  32767. this.onCompiled(effect);
  32768. }
  32769. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  32770. }.bind(this);
  32771. var join = defines.toString();
  32772. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  32773. attributes: attribs,
  32774. uniformsNames: uniforms,
  32775. uniformBuffersNames: uniformBuffers,
  32776. samplers: samplers,
  32777. defines: join,
  32778. fallbacks: fallbacks,
  32779. onCompiled: onCompiled,
  32780. onError: this.onError,
  32781. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  32782. }, engine), defines);
  32783. this.buildUniformLayout();
  32784. }
  32785. if (!subMesh.effect.isReady()) {
  32786. return false;
  32787. }
  32788. defines._renderId = scene.getRenderId();
  32789. this._wasPreviouslyReady = true;
  32790. return true;
  32791. };
  32792. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  32793. // Order is important !
  32794. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  32795. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  32796. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  32797. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  32798. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  32799. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  32800. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  32801. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  32802. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  32803. this._uniformBuffer.addUniform("vBumpInfos", 3);
  32804. this._uniformBuffer.addUniform("albedoMatrix", 16);
  32805. this._uniformBuffer.addUniform("ambientMatrix", 16);
  32806. this._uniformBuffer.addUniform("opacityMatrix", 16);
  32807. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  32808. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  32809. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  32810. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  32811. this._uniformBuffer.addUniform("bumpMatrix", 16);
  32812. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  32813. this._uniformBuffer.addUniform("refractionMatrix", 16);
  32814. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  32815. this._uniformBuffer.addUniform("vReflectionColor", 3);
  32816. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  32817. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  32818. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  32819. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  32820. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  32821. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  32822. this._uniformBuffer.addUniform("pointSize", 1);
  32823. this._uniformBuffer.create();
  32824. };
  32825. PBRBaseMaterial.prototype.unbind = function () {
  32826. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  32827. this._uniformBuffer.setTexture("reflectionSampler", null);
  32828. }
  32829. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  32830. this._uniformBuffer.setTexture("refractionSampler", null);
  32831. }
  32832. _super.prototype.unbind.call(this);
  32833. };
  32834. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  32835. this._activeEffect.setMatrix("world", world);
  32836. };
  32837. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32838. var scene = this.getScene();
  32839. var defines = subMesh._materialDefines;
  32840. if (!defines) {
  32841. return;
  32842. }
  32843. var effect = subMesh.effect;
  32844. this._activeEffect = effect;
  32845. // Matrices
  32846. this.bindOnlyWorldMatrix(world);
  32847. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  32848. // Bones
  32849. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  32850. if (mustRebind) {
  32851. this._uniformBuffer.bindToEffect(effect, "Material");
  32852. this.bindViewProjection(effect);
  32853. var reflectionTexture = this._getReflectionTexture();
  32854. var refractionTexture = this._getRefractionTexture();
  32855. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  32856. // Texture uniforms
  32857. if (scene.texturesEnabled) {
  32858. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32859. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  32860. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  32861. }
  32862. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32863. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  32864. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  32865. }
  32866. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32867. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  32868. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  32869. }
  32870. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32871. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  32872. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  32873. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  32874. var polynomials = reflectionTexture.sphericalPolynomial;
  32875. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  32876. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  32877. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  32878. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  32879. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  32880. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  32881. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  32882. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  32883. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  32884. }
  32885. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  32886. }
  32887. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32888. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  32889. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  32890. }
  32891. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32892. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  32893. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  32894. }
  32895. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32896. if (this._metallicTexture) {
  32897. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  32898. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  32899. }
  32900. else if (this._reflectivityTexture) {
  32901. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  32902. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  32903. }
  32904. if (this._microSurfaceTexture) {
  32905. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  32906. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  32907. }
  32908. }
  32909. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32910. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  32911. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  32912. if (scene._mirroredCameraPosition) {
  32913. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  32914. }
  32915. else {
  32916. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  32917. }
  32918. }
  32919. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32920. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  32921. var depth = 1.0;
  32922. if (!refractionTexture.isCube) {
  32923. if (refractionTexture.depth) {
  32924. depth = refractionTexture.depth;
  32925. }
  32926. }
  32927. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  32928. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  32929. }
  32930. }
  32931. // Point size
  32932. if (this.pointsCloud) {
  32933. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  32934. }
  32935. // Colors
  32936. if (defines.METALLICWORKFLOW) {
  32937. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  32938. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  32939. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  32940. }
  32941. else {
  32942. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  32943. }
  32944. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  32945. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  32946. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  32947. // Misc
  32948. this._lightingInfos.x = this._directIntensity;
  32949. this._lightingInfos.y = this._emissiveIntensity;
  32950. this._lightingInfos.z = this._environmentIntensity;
  32951. this._lightingInfos.w = this._specularIntensity;
  32952. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  32953. }
  32954. // Textures
  32955. if (scene.texturesEnabled) {
  32956. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32957. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  32958. }
  32959. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32960. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  32961. }
  32962. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32963. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  32964. }
  32965. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32966. if (defines.LODBASEDMICROSFURACE) {
  32967. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  32968. }
  32969. else {
  32970. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  32971. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  32972. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  32973. }
  32974. }
  32975. if (defines.ENVIRONMENTBRDF) {
  32976. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  32977. }
  32978. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32979. if (defines.LODBASEDMICROSFURACE) {
  32980. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  32981. }
  32982. else {
  32983. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  32984. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  32985. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  32986. }
  32987. }
  32988. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32989. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  32990. }
  32991. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32992. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  32993. }
  32994. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32995. if (this._metallicTexture) {
  32996. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  32997. }
  32998. else if (this._reflectivityTexture) {
  32999. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  33000. }
  33001. if (this._microSurfaceTexture) {
  33002. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  33003. }
  33004. }
  33005. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  33006. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  33007. }
  33008. }
  33009. // Clip plane
  33010. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  33011. // Colors
  33012. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  33013. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  33014. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  33015. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  33016. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  33017. }
  33018. if (mustRebind || !this.isFrozen) {
  33019. // Lights
  33020. if (scene.lightsEnabled && !this._disableLighting) {
  33021. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  33022. }
  33023. // View
  33024. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  33025. this.bindView(effect);
  33026. }
  33027. // Fog
  33028. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  33029. // Morph targets
  33030. if (defines.NUM_MORPH_INFLUENCERS) {
  33031. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  33032. }
  33033. // image processing
  33034. this._imageProcessingConfiguration.bind(this._activeEffect);
  33035. // Log. depth
  33036. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  33037. }
  33038. this._uniformBuffer.update();
  33039. this._afterBind(mesh);
  33040. scene = null;
  33041. };
  33042. PBRBaseMaterial.prototype.getAnimatables = function () {
  33043. var results = [];
  33044. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  33045. results.push(this._albedoTexture);
  33046. }
  33047. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  33048. results.push(this._ambientTexture);
  33049. }
  33050. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  33051. results.push(this._opacityTexture);
  33052. }
  33053. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  33054. results.push(this._reflectionTexture);
  33055. }
  33056. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  33057. results.push(this._emissiveTexture);
  33058. }
  33059. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  33060. results.push(this._metallicTexture);
  33061. }
  33062. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  33063. results.push(this._reflectivityTexture);
  33064. }
  33065. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  33066. results.push(this._bumpTexture);
  33067. }
  33068. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  33069. results.push(this._lightmapTexture);
  33070. }
  33071. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  33072. results.push(this._refractionTexture);
  33073. }
  33074. return results;
  33075. };
  33076. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  33077. if (this._reflectionTexture) {
  33078. return this._reflectionTexture;
  33079. }
  33080. return this.getScene().environmentTexture;
  33081. };
  33082. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  33083. if (this._refractionTexture) {
  33084. return this._refractionTexture;
  33085. }
  33086. if (this._linkRefractionWithTransparency) {
  33087. return this.getScene().environmentTexture;
  33088. }
  33089. return null;
  33090. };
  33091. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  33092. if (forceDisposeTextures) {
  33093. if (this._albedoTexture) {
  33094. this._albedoTexture.dispose();
  33095. }
  33096. if (this._ambientTexture) {
  33097. this._ambientTexture.dispose();
  33098. }
  33099. if (this._opacityTexture) {
  33100. this._opacityTexture.dispose();
  33101. }
  33102. if (this._reflectionTexture) {
  33103. this._reflectionTexture.dispose();
  33104. }
  33105. if (this._environmentBRDFTexture) {
  33106. this._environmentBRDFTexture.dispose();
  33107. }
  33108. if (this._emissiveTexture) {
  33109. this._emissiveTexture.dispose();
  33110. }
  33111. if (this._metallicTexture) {
  33112. this._metallicTexture.dispose();
  33113. }
  33114. if (this._reflectivityTexture) {
  33115. this._reflectivityTexture.dispose();
  33116. }
  33117. if (this._bumpTexture) {
  33118. this._bumpTexture.dispose();
  33119. }
  33120. if (this._lightmapTexture) {
  33121. this._lightmapTexture.dispose();
  33122. }
  33123. if (this._refractionTexture) {
  33124. this._refractionTexture.dispose();
  33125. }
  33126. }
  33127. this._renderTargets.dispose();
  33128. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33129. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33130. }
  33131. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  33132. };
  33133. return PBRBaseMaterial;
  33134. }(BABYLON.PushMaterial));
  33135. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  33136. __decorate([
  33137. BABYLON.serializeAsImageProcessingConfiguration()
  33138. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  33139. __decorate([
  33140. BABYLON.serialize()
  33141. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  33142. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  33143. })(BABYLON || (BABYLON = {}));
  33144. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  33145. var BABYLON;
  33146. (function (BABYLON) {
  33147. var Internals;
  33148. (function (Internals) {
  33149. /**
  33150. * The Physically based simple base material of BJS.
  33151. *
  33152. * This enables better naming and convention enforcements on top of the pbrMaterial.
  33153. * It is used as the base class for both the specGloss and metalRough conventions.
  33154. */
  33155. var PBRBaseSimpleMaterial = (function (_super) {
  33156. __extends(PBRBaseSimpleMaterial, _super);
  33157. /**
  33158. * Instantiates a new PBRMaterial instance.
  33159. *
  33160. * @param name The material name
  33161. * @param scene The scene the material will be use in.
  33162. */
  33163. function PBRBaseSimpleMaterial(name, scene) {
  33164. var _this = _super.call(this, name, scene) || this;
  33165. /**
  33166. * Number of Simultaneous lights allowed on the material.
  33167. */
  33168. _this.maxSimultaneousLights = 4;
  33169. /**
  33170. * If sets to true, disables all the lights affecting the material.
  33171. */
  33172. _this.disableLighting = false;
  33173. /**
  33174. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33175. */
  33176. _this.invertNormalMapX = false;
  33177. /**
  33178. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33179. */
  33180. _this.invertNormalMapY = false;
  33181. /**
  33182. * Emissivie color used to self-illuminate the model.
  33183. */
  33184. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33185. /**
  33186. * Occlusion Channel Strenght.
  33187. */
  33188. _this.occlusionStrength = 1.0;
  33189. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  33190. _this._useAmbientInGrayScale = true;
  33191. return _this;
  33192. }
  33193. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  33194. /**
  33195. * Gets the current transparency mode.
  33196. */
  33197. get: function () {
  33198. return this._transparencyMode;
  33199. },
  33200. /**
  33201. * Sets the transparency mode of the material.
  33202. */
  33203. set: function (value) {
  33204. if (this._transparencyMode === value) {
  33205. return;
  33206. }
  33207. this._transparencyMode = value;
  33208. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  33209. this._forceAlphaTest = true;
  33210. }
  33211. else {
  33212. this._forceAlphaTest = false;
  33213. }
  33214. this._markAllSubMeshesAsTexturesDirty();
  33215. },
  33216. enumerable: true,
  33217. configurable: true
  33218. });
  33219. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  33220. /**
  33221. * Gets the current double sided mode.
  33222. */
  33223. get: function () {
  33224. return this._twoSidedLighting;
  33225. },
  33226. /**
  33227. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33228. */
  33229. set: function (value) {
  33230. if (this._twoSidedLighting === value) {
  33231. return;
  33232. }
  33233. this._twoSidedLighting = value;
  33234. this.backFaceCulling = !value;
  33235. this._markAllSubMeshesAsTexturesDirty();
  33236. },
  33237. enumerable: true,
  33238. configurable: true
  33239. });
  33240. /**
  33241. * Specifies wether or not the alpha value of the albedo texture should be used.
  33242. */
  33243. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  33244. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  33245. };
  33246. /**
  33247. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  33248. */
  33249. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  33250. if (this._linkRefractionWithTransparency) {
  33251. return false;
  33252. }
  33253. return (this.alpha < 1.0) ||
  33254. (this._shouldUseAlphaFromAlbedoTexture() &&
  33255. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  33256. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  33257. };
  33258. /**
  33259. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  33260. */
  33261. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  33262. if (this._linkRefractionWithTransparency) {
  33263. return false;
  33264. }
  33265. return this._shouldUseAlphaFromAlbedoTexture() &&
  33266. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  33267. };
  33268. /**
  33269. * Return the active textures of the material.
  33270. */
  33271. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  33272. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33273. if (this.environmentTexture) {
  33274. activeTextures.push(this.environmentTexture);
  33275. }
  33276. if (this.normalTexture) {
  33277. activeTextures.push(this.normalTexture);
  33278. }
  33279. if (this.emissiveTexture) {
  33280. activeTextures.push(this.emissiveTexture);
  33281. }
  33282. if (this.occlusionTexture) {
  33283. activeTextures.push(this.occlusionTexture);
  33284. }
  33285. return activeTextures;
  33286. };
  33287. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  33288. return "PBRBaseSimpleMaterial";
  33289. };
  33290. return PBRBaseSimpleMaterial;
  33291. }(BABYLON.PBRBaseMaterial));
  33292. __decorate([
  33293. BABYLON.serialize(),
  33294. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33295. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  33296. __decorate([
  33297. BABYLON.serialize(),
  33298. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33299. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  33300. __decorate([
  33301. BABYLON.serializeAsTexture(),
  33302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  33303. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  33304. __decorate([
  33305. BABYLON.serialize(),
  33306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33307. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  33308. __decorate([
  33309. BABYLON.serialize(),
  33310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33311. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  33312. __decorate([
  33313. BABYLON.serializeAsTexture(),
  33314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  33315. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  33316. __decorate([
  33317. BABYLON.serializeAsColor3("emissive"),
  33318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33319. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  33320. __decorate([
  33321. BABYLON.serializeAsTexture(),
  33322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33323. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  33324. __decorate([
  33325. BABYLON.serialize(),
  33326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  33327. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  33328. __decorate([
  33329. BABYLON.serializeAsTexture(),
  33330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  33331. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  33332. __decorate([
  33333. BABYLON.serialize(),
  33334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  33335. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  33336. __decorate([
  33337. BABYLON.serialize()
  33338. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  33339. __decorate([
  33340. BABYLON.serialize()
  33341. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  33342. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  33343. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33344. })(BABYLON || (BABYLON = {}));
  33345. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  33346. var BABYLON;
  33347. (function (BABYLON) {
  33348. /**
  33349. * The Physically based material of BJS.
  33350. *
  33351. * This offers the main features of a standard PBR material.
  33352. * For more information, please refer to the documentation :
  33353. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  33354. */
  33355. var PBRMaterial = (function (_super) {
  33356. __extends(PBRMaterial, _super);
  33357. /**
  33358. * Instantiates a new PBRMaterial instance.
  33359. *
  33360. * @param name The material name
  33361. * @param scene The scene the material will be use in.
  33362. */
  33363. function PBRMaterial(name, scene) {
  33364. var _this = _super.call(this, name, scene) || this;
  33365. /**
  33366. * Intensity of the direct lights e.g. the four lights available in your scene.
  33367. * This impacts both the direct diffuse and specular highlights.
  33368. */
  33369. _this.directIntensity = 1.0;
  33370. /**
  33371. * Intensity of the emissive part of the material.
  33372. * This helps controlling the emissive effect without modifying the emissive color.
  33373. */
  33374. _this.emissiveIntensity = 1.0;
  33375. /**
  33376. * Intensity of the environment e.g. how much the environment will light the object
  33377. * either through harmonics for rough material or through the refelction for shiny ones.
  33378. */
  33379. _this.environmentIntensity = 1.0;
  33380. /**
  33381. * This is a special control allowing the reduction of the specular highlights coming from the
  33382. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  33383. */
  33384. _this.specularIntensity = 1.0;
  33385. /**
  33386. * Debug Control allowing disabling the bump map on this material.
  33387. */
  33388. _this.disableBumpMap = false;
  33389. /**
  33390. * AKA Occlusion Texture Intensity in other nomenclature.
  33391. */
  33392. _this.ambientTextureStrength = 1.0;
  33393. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33394. /**
  33395. * AKA Diffuse Color in other nomenclature.
  33396. */
  33397. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  33398. /**
  33399. * AKA Specular Color in other nomenclature.
  33400. */
  33401. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  33402. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  33403. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33404. /**
  33405. * AKA Glossiness in other nomenclature.
  33406. */
  33407. _this.microSurface = 1.0;
  33408. /**
  33409. * source material index of refraction (IOR)' / 'destination material IOR.
  33410. */
  33411. _this.indexOfRefraction = 0.66;
  33412. /**
  33413. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  33414. */
  33415. _this.invertRefractionY = false;
  33416. /**
  33417. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  33418. * Materials half opaque for instance using refraction could benefit from this control.
  33419. */
  33420. _this.linkRefractionWithTransparency = false;
  33421. _this.useLightmapAsShadowmap = false;
  33422. /**
  33423. * Specifies that the alpha is coming form the albedo channel alpha channel.
  33424. */
  33425. _this.useAlphaFromAlbedoTexture = false;
  33426. /**
  33427. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  33428. */
  33429. _this.forceAlphaTest = false;
  33430. /**
  33431. * Defines the alpha limits in alpha test mode.
  33432. */
  33433. _this.alphaCutOff = 0.4;
  33434. /**
  33435. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  33436. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  33437. */
  33438. _this.useSpecularOverAlpha = true;
  33439. /**
  33440. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  33441. */
  33442. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  33443. /**
  33444. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  33445. */
  33446. _this.useRoughnessFromMetallicTextureAlpha = true;
  33447. /**
  33448. * Specifies if the metallic texture contains the roughness information in its green channel.
  33449. */
  33450. _this.useRoughnessFromMetallicTextureGreen = false;
  33451. /**
  33452. * Specifies if the metallic texture contains the metallness information in its blue channel.
  33453. */
  33454. _this.useMetallnessFromMetallicTextureBlue = false;
  33455. /**
  33456. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  33457. */
  33458. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  33459. /**
  33460. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  33461. */
  33462. _this.useAmbientInGrayScale = false;
  33463. /**
  33464. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  33465. * The material will try to infer what glossiness each pixel should be.
  33466. */
  33467. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  33468. /**
  33469. * BJS is using an harcoded light falloff based on a manually sets up range.
  33470. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  33471. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  33472. */
  33473. _this.usePhysicalLightFalloff = true;
  33474. /**
  33475. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  33476. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  33477. */
  33478. _this.useRadianceOverAlpha = true;
  33479. /**
  33480. * Allows using the bump map in parallax mode.
  33481. */
  33482. _this.useParallax = false;
  33483. /**
  33484. * Allows using the bump map in parallax occlusion mode.
  33485. */
  33486. _this.useParallaxOcclusion = false;
  33487. /**
  33488. * Controls the scale bias of the parallax mode.
  33489. */
  33490. _this.parallaxScaleBias = 0.05;
  33491. /**
  33492. * If sets to true, disables all the lights affecting the material.
  33493. */
  33494. _this.disableLighting = false;
  33495. /**
  33496. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  33497. */
  33498. _this.forceIrradianceInFragment = false;
  33499. /**
  33500. * Number of Simultaneous lights allowed on the material.
  33501. */
  33502. _this.maxSimultaneousLights = 4;
  33503. /**
  33504. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33505. */
  33506. _this.invertNormalMapX = false;
  33507. /**
  33508. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33509. */
  33510. _this.invertNormalMapY = false;
  33511. /**
  33512. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33513. */
  33514. _this.twoSidedLighting = false;
  33515. /**
  33516. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  33517. * in your scene composition.
  33518. */
  33519. _this.preMultiplyAlpha = false;
  33520. /**
  33521. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33522. * And/Or occlude the blended part.
  33523. */
  33524. _this.useAlphaFresnel = false;
  33525. /**
  33526. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33527. * And/Or occlude the blended part.
  33528. */
  33529. _this.environmentBRDFTexture = null;
  33530. /**
  33531. * Force normal to face away from face.
  33532. * (Temporary internal fix to remove before 3.1)
  33533. */
  33534. _this.forceNormalForward = false;
  33535. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  33536. return _this;
  33537. }
  33538. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  33539. /**
  33540. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  33541. */
  33542. get: function () {
  33543. return this._PBRMATERIAL_OPAQUE;
  33544. },
  33545. enumerable: true,
  33546. configurable: true
  33547. });
  33548. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  33549. /**
  33550. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  33551. */
  33552. get: function () {
  33553. return this._PBRMATERIAL_ALPHATEST;
  33554. },
  33555. enumerable: true,
  33556. configurable: true
  33557. });
  33558. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  33559. /**
  33560. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33561. */
  33562. get: function () {
  33563. return this._PBRMATERIAL_ALPHABLEND;
  33564. },
  33565. enumerable: true,
  33566. configurable: true
  33567. });
  33568. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  33569. /**
  33570. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33571. * They are also discarded below the alpha cutoff threshold to improve performances.
  33572. */
  33573. get: function () {
  33574. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  33575. },
  33576. enumerable: true,
  33577. configurable: true
  33578. });
  33579. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  33580. /**
  33581. * Gets the image processing configuration used either in this material.
  33582. */
  33583. get: function () {
  33584. return this._imageProcessingConfiguration;
  33585. },
  33586. /**
  33587. * Sets the Default image processing configuration used either in the this material.
  33588. *
  33589. * If sets to null, the scene one is in use.
  33590. */
  33591. set: function (value) {
  33592. this._attachImageProcessingConfiguration(value);
  33593. // Ensure the effect will be rebuilt.
  33594. this._markAllSubMeshesAsTexturesDirty();
  33595. },
  33596. enumerable: true,
  33597. configurable: true
  33598. });
  33599. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  33600. /**
  33601. * Gets wether the color curves effect is enabled.
  33602. */
  33603. get: function () {
  33604. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33605. },
  33606. /**
  33607. * Sets wether the color curves effect is enabled.
  33608. */
  33609. set: function (value) {
  33610. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33611. },
  33612. enumerable: true,
  33613. configurable: true
  33614. });
  33615. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  33616. /**
  33617. * Gets wether the color grading effect is enabled.
  33618. */
  33619. get: function () {
  33620. return this.imageProcessingConfiguration.colorGradingEnabled;
  33621. },
  33622. /**
  33623. * Gets wether the color grading effect is enabled.
  33624. */
  33625. set: function (value) {
  33626. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33627. },
  33628. enumerable: true,
  33629. configurable: true
  33630. });
  33631. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  33632. /**
  33633. * Gets wether tonemapping is enabled or not.
  33634. */
  33635. get: function () {
  33636. return this._imageProcessingConfiguration.toneMappingEnabled;
  33637. },
  33638. /**
  33639. * Sets wether tonemapping is enabled or not
  33640. */
  33641. set: function (value) {
  33642. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33643. },
  33644. enumerable: true,
  33645. configurable: true
  33646. });
  33647. ;
  33648. ;
  33649. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  33650. /**
  33651. * The camera exposure used on this material.
  33652. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33653. * This corresponds to a photographic exposure.
  33654. */
  33655. get: function () {
  33656. return this._imageProcessingConfiguration.exposure;
  33657. },
  33658. /**
  33659. * The camera exposure used on this material.
  33660. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33661. * This corresponds to a photographic exposure.
  33662. */
  33663. set: function (value) {
  33664. this._imageProcessingConfiguration.exposure = value;
  33665. },
  33666. enumerable: true,
  33667. configurable: true
  33668. });
  33669. ;
  33670. ;
  33671. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  33672. /**
  33673. * Gets The camera contrast used on this material.
  33674. */
  33675. get: function () {
  33676. return this._imageProcessingConfiguration.contrast;
  33677. },
  33678. /**
  33679. * Sets The camera contrast used on this material.
  33680. */
  33681. set: function (value) {
  33682. this._imageProcessingConfiguration.contrast = value;
  33683. },
  33684. enumerable: true,
  33685. configurable: true
  33686. });
  33687. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  33688. /**
  33689. * Gets the Color Grading 2D Lookup Texture.
  33690. */
  33691. get: function () {
  33692. return this._imageProcessingConfiguration.colorGradingTexture;
  33693. },
  33694. /**
  33695. * Sets the Color Grading 2D Lookup Texture.
  33696. */
  33697. set: function (value) {
  33698. this._imageProcessingConfiguration.colorGradingTexture = value;
  33699. },
  33700. enumerable: true,
  33701. configurable: true
  33702. });
  33703. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  33704. /**
  33705. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33706. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33707. * 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;
  33708. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33709. */
  33710. get: function () {
  33711. return this._imageProcessingConfiguration.colorCurves;
  33712. },
  33713. /**
  33714. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33715. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33716. * 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;
  33717. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33718. */
  33719. set: function (value) {
  33720. this._imageProcessingConfiguration.colorCurves = value;
  33721. },
  33722. enumerable: true,
  33723. configurable: true
  33724. });
  33725. PBRMaterial.prototype.getClassName = function () {
  33726. return "PBRMaterial";
  33727. };
  33728. PBRMaterial.prototype.getActiveTextures = function () {
  33729. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33730. if (this._albedoTexture) {
  33731. activeTextures.push(this._albedoTexture);
  33732. }
  33733. if (this._ambientTexture) {
  33734. activeTextures.push(this._ambientTexture);
  33735. }
  33736. if (this._opacityTexture) {
  33737. activeTextures.push(this._opacityTexture);
  33738. }
  33739. if (this._reflectionTexture) {
  33740. activeTextures.push(this._reflectionTexture);
  33741. }
  33742. if (this._emissiveTexture) {
  33743. activeTextures.push(this._emissiveTexture);
  33744. }
  33745. if (this._reflectivityTexture) {
  33746. activeTextures.push(this._reflectivityTexture);
  33747. }
  33748. if (this._metallicTexture) {
  33749. activeTextures.push(this._metallicTexture);
  33750. }
  33751. if (this._microSurfaceTexture) {
  33752. activeTextures.push(this._microSurfaceTexture);
  33753. }
  33754. if (this._bumpTexture) {
  33755. activeTextures.push(this._bumpTexture);
  33756. }
  33757. if (this._lightmapTexture) {
  33758. activeTextures.push(this._lightmapTexture);
  33759. }
  33760. if (this._refractionTexture) {
  33761. activeTextures.push(this._refractionTexture);
  33762. }
  33763. return activeTextures;
  33764. };
  33765. PBRMaterial.prototype.hasTexture = function (texture) {
  33766. if (_super.prototype.hasTexture.call(this, texture)) {
  33767. return true;
  33768. }
  33769. if (this._albedoTexture === texture) {
  33770. return true;
  33771. }
  33772. if (this._ambientTexture === texture) {
  33773. return true;
  33774. }
  33775. if (this._opacityTexture === texture) {
  33776. return true;
  33777. }
  33778. if (this._reflectionTexture === texture) {
  33779. return true;
  33780. }
  33781. if (this._reflectivityTexture === texture) {
  33782. return true;
  33783. }
  33784. if (this._metallicTexture === texture) {
  33785. return true;
  33786. }
  33787. if (this._microSurfaceTexture === texture) {
  33788. return true;
  33789. }
  33790. if (this._bumpTexture === texture) {
  33791. return true;
  33792. }
  33793. if (this._lightmapTexture === texture) {
  33794. return true;
  33795. }
  33796. if (this._refractionTexture === texture) {
  33797. return true;
  33798. }
  33799. return false;
  33800. };
  33801. PBRMaterial.prototype.clone = function (name) {
  33802. var _this = this;
  33803. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  33804. };
  33805. PBRMaterial.prototype.serialize = function () {
  33806. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33807. serializationObject.customType = "BABYLON.PBRMaterial";
  33808. return serializationObject;
  33809. };
  33810. // Statics
  33811. PBRMaterial.Parse = function (source, scene, rootUrl) {
  33812. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  33813. };
  33814. return PBRMaterial;
  33815. }(BABYLON.PBRBaseMaterial));
  33816. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  33817. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  33818. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  33819. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  33820. __decorate([
  33821. BABYLON.serialize(),
  33822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33823. ], PBRMaterial.prototype, "directIntensity", void 0);
  33824. __decorate([
  33825. BABYLON.serialize(),
  33826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33827. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  33828. __decorate([
  33829. BABYLON.serialize(),
  33830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33831. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  33832. __decorate([
  33833. BABYLON.serialize(),
  33834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33835. ], PBRMaterial.prototype, "specularIntensity", void 0);
  33836. __decorate([
  33837. BABYLON.serialize(),
  33838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33839. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  33840. __decorate([
  33841. BABYLON.serializeAsTexture(),
  33842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33843. ], PBRMaterial.prototype, "albedoTexture", void 0);
  33844. __decorate([
  33845. BABYLON.serializeAsTexture(),
  33846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33847. ], PBRMaterial.prototype, "ambientTexture", void 0);
  33848. __decorate([
  33849. BABYLON.serialize(),
  33850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33851. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  33852. __decorate([
  33853. BABYLON.serializeAsTexture(),
  33854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33855. ], PBRMaterial.prototype, "opacityTexture", void 0);
  33856. __decorate([
  33857. BABYLON.serializeAsTexture(),
  33858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33859. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  33860. __decorate([
  33861. BABYLON.serializeAsTexture(),
  33862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33863. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  33864. __decorate([
  33865. BABYLON.serializeAsTexture(),
  33866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33867. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  33868. __decorate([
  33869. BABYLON.serializeAsTexture(),
  33870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33871. ], PBRMaterial.prototype, "metallicTexture", void 0);
  33872. __decorate([
  33873. BABYLON.serialize(),
  33874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33875. ], PBRMaterial.prototype, "metallic", void 0);
  33876. __decorate([
  33877. BABYLON.serialize(),
  33878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33879. ], PBRMaterial.prototype, "roughness", void 0);
  33880. __decorate([
  33881. BABYLON.serializeAsTexture(),
  33882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33883. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  33884. __decorate([
  33885. BABYLON.serializeAsTexture(),
  33886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33887. ], PBRMaterial.prototype, "bumpTexture", void 0);
  33888. __decorate([
  33889. BABYLON.serializeAsTexture(),
  33890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  33891. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  33892. __decorate([
  33893. BABYLON.serializeAsTexture(),
  33894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33895. ], PBRMaterial.prototype, "refractionTexture", void 0);
  33896. __decorate([
  33897. BABYLON.serializeAsColor3("ambient"),
  33898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33899. ], PBRMaterial.prototype, "ambientColor", void 0);
  33900. __decorate([
  33901. BABYLON.serializeAsColor3("albedo"),
  33902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33903. ], PBRMaterial.prototype, "albedoColor", void 0);
  33904. __decorate([
  33905. BABYLON.serializeAsColor3("reflectivity"),
  33906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33907. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  33908. __decorate([
  33909. BABYLON.serializeAsColor3("reflection"),
  33910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33911. ], PBRMaterial.prototype, "reflectionColor", void 0);
  33912. __decorate([
  33913. BABYLON.serializeAsColor3("emissive"),
  33914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33915. ], PBRMaterial.prototype, "emissiveColor", void 0);
  33916. __decorate([
  33917. BABYLON.serialize(),
  33918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33919. ], PBRMaterial.prototype, "microSurface", void 0);
  33920. __decorate([
  33921. BABYLON.serialize(),
  33922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33923. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  33924. __decorate([
  33925. BABYLON.serialize(),
  33926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33927. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  33928. __decorate([
  33929. BABYLON.serialize(),
  33930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33931. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  33932. __decorate([
  33933. BABYLON.serialize(),
  33934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33935. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  33936. __decorate([
  33937. BABYLON.serialize(),
  33938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33939. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  33940. __decorate([
  33941. BABYLON.serialize(),
  33942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33943. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  33944. __decorate([
  33945. BABYLON.serialize(),
  33946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33947. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  33948. __decorate([
  33949. BABYLON.serialize(),
  33950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33951. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  33952. __decorate([
  33953. BABYLON.serialize(),
  33954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33955. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  33956. __decorate([
  33957. BABYLON.serialize(),
  33958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33959. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  33960. __decorate([
  33961. BABYLON.serialize(),
  33962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33963. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  33964. __decorate([
  33965. BABYLON.serialize(),
  33966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33967. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  33968. __decorate([
  33969. BABYLON.serialize(),
  33970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33971. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  33972. __decorate([
  33973. BABYLON.serialize(),
  33974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33975. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  33976. __decorate([
  33977. BABYLON.serialize(),
  33978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33979. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  33980. __decorate([
  33981. BABYLON.serialize(),
  33982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33983. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  33984. __decorate([
  33985. BABYLON.serialize(),
  33986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33987. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  33988. __decorate([
  33989. BABYLON.serialize(),
  33990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33991. ], PBRMaterial.prototype, "useParallax", void 0);
  33992. __decorate([
  33993. BABYLON.serialize(),
  33994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33995. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  33996. __decorate([
  33997. BABYLON.serialize(),
  33998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33999. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  34000. __decorate([
  34001. BABYLON.serialize(),
  34002. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34003. ], PBRMaterial.prototype, "disableLighting", void 0);
  34004. __decorate([
  34005. BABYLON.serialize(),
  34006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34007. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  34008. __decorate([
  34009. BABYLON.serialize(),
  34010. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34011. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  34012. __decorate([
  34013. BABYLON.serialize(),
  34014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34015. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  34016. __decorate([
  34017. BABYLON.serialize(),
  34018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34019. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  34020. __decorate([
  34021. BABYLON.serialize(),
  34022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34023. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  34024. __decorate([
  34025. BABYLON.serialize(),
  34026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34027. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  34028. __decorate([
  34029. BABYLON.serialize(),
  34030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34031. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  34032. __decorate([
  34033. BABYLON.serializeAsTexture(),
  34034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34035. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  34036. __decorate([
  34037. BABYLON.serialize(),
  34038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34039. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  34040. BABYLON.PBRMaterial = PBRMaterial;
  34041. })(BABYLON || (BABYLON = {}));
  34042. //# sourceMappingURL=babylon.pbrMaterial.js.map
  34043. var BABYLON;
  34044. (function (BABYLON) {
  34045. /**
  34046. * The PBR material of BJS following the metal roughness convention.
  34047. *
  34048. * This fits to the PBR convention in the GLTF definition:
  34049. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  34050. */
  34051. var PBRMetallicRoughnessMaterial = (function (_super) {
  34052. __extends(PBRMetallicRoughnessMaterial, _super);
  34053. /**
  34054. * Instantiates a new PBRMetalRoughnessMaterial instance.
  34055. *
  34056. * @param name The material name
  34057. * @param scene The scene the material will be use in.
  34058. */
  34059. function PBRMetallicRoughnessMaterial(name, scene) {
  34060. var _this = _super.call(this, name, scene) || this;
  34061. _this._useRoughnessFromMetallicTextureAlpha = false;
  34062. _this._useRoughnessFromMetallicTextureGreen = true;
  34063. _this._useMetallnessFromMetallicTextureBlue = true;
  34064. return _this;
  34065. }
  34066. /**
  34067. * Return the currrent class name of the material.
  34068. */
  34069. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  34070. return "PBRMetallicRoughnessMaterial";
  34071. };
  34072. /**
  34073. * Return the active textures of the material.
  34074. */
  34075. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  34076. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34077. if (this.baseTexture) {
  34078. activeTextures.push(this.baseTexture);
  34079. }
  34080. if (this.metallicRoughnessTexture) {
  34081. activeTextures.push(this.metallicRoughnessTexture);
  34082. }
  34083. return activeTextures;
  34084. };
  34085. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  34086. if (_super.prototype.hasTexture.call(this, texture)) {
  34087. return true;
  34088. }
  34089. if (this.baseTexture === texture) {
  34090. return true;
  34091. }
  34092. if (this.metallicRoughnessTexture === texture) {
  34093. return true;
  34094. }
  34095. return false;
  34096. };
  34097. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  34098. var _this = this;
  34099. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  34100. };
  34101. /**
  34102. * Serialize the material to a parsable JSON object.
  34103. */
  34104. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  34105. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  34106. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  34107. return serializationObject;
  34108. };
  34109. /**
  34110. * Parses a JSON object correponding to the serialize function.
  34111. */
  34112. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  34113. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  34114. };
  34115. return PBRMetallicRoughnessMaterial;
  34116. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  34117. __decorate([
  34118. BABYLON.serializeAsColor3(),
  34119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  34120. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  34121. __decorate([
  34122. BABYLON.serializeAsTexture(),
  34123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  34124. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  34125. __decorate([
  34126. BABYLON.serialize(),
  34127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34128. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  34129. __decorate([
  34130. BABYLON.serialize(),
  34131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34132. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  34133. __decorate([
  34134. BABYLON.serializeAsTexture(),
  34135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  34136. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  34137. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  34138. })(BABYLON || (BABYLON = {}));
  34139. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  34140. var BABYLON;
  34141. (function (BABYLON) {
  34142. /**
  34143. * The PBR material of BJS following the specular glossiness convention.
  34144. *
  34145. * This fits to the PBR convention in the GLTF definition:
  34146. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  34147. */
  34148. var PBRSpecularGlossinessMaterial = (function (_super) {
  34149. __extends(PBRSpecularGlossinessMaterial, _super);
  34150. /**
  34151. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  34152. *
  34153. * @param name The material name
  34154. * @param scene The scene the material will be use in.
  34155. */
  34156. function PBRSpecularGlossinessMaterial(name, scene) {
  34157. var _this = _super.call(this, name, scene) || this;
  34158. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  34159. return _this;
  34160. }
  34161. /**
  34162. * Return the currrent class name of the material.
  34163. */
  34164. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  34165. return "PBRSpecularGlossinessMaterial";
  34166. };
  34167. /**
  34168. * Return the active textures of the material.
  34169. */
  34170. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  34171. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34172. if (this.diffuseTexture) {
  34173. activeTextures.push(this.diffuseTexture);
  34174. }
  34175. if (this.specularGlossinessTexture) {
  34176. activeTextures.push(this.specularGlossinessTexture);
  34177. }
  34178. return activeTextures;
  34179. };
  34180. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  34181. if (_super.prototype.hasTexture.call(this, texture)) {
  34182. return true;
  34183. }
  34184. if (this.diffuseTexture === texture) {
  34185. return true;
  34186. }
  34187. if (this.specularGlossinessTexture === texture) {
  34188. return true;
  34189. }
  34190. return false;
  34191. };
  34192. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  34193. var _this = this;
  34194. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  34195. };
  34196. /**
  34197. * Serialize the material to a parsable JSON object.
  34198. */
  34199. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  34200. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  34201. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  34202. return serializationObject;
  34203. };
  34204. /**
  34205. * Parses a JSON object correponding to the serialize function.
  34206. */
  34207. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  34208. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  34209. };
  34210. return PBRSpecularGlossinessMaterial;
  34211. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  34212. __decorate([
  34213. BABYLON.serializeAsColor3("diffuse"),
  34214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  34215. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  34216. __decorate([
  34217. BABYLON.serializeAsTexture(),
  34218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  34219. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  34220. __decorate([
  34221. BABYLON.serializeAsColor3("specular"),
  34222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  34223. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  34224. __decorate([
  34225. BABYLON.serialize(),
  34226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  34227. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  34228. __decorate([
  34229. BABYLON.serializeAsTexture(),
  34230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  34231. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  34232. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  34233. })(BABYLON || (BABYLON = {}));
  34234. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  34235. var BABYLON;
  34236. (function (BABYLON) {
  34237. BABYLON.CameraInputTypes = {};
  34238. var CameraInputsManager = (function () {
  34239. function CameraInputsManager(camera) {
  34240. this.attached = {};
  34241. this.camera = camera;
  34242. this.checkInputs = function () { };
  34243. }
  34244. CameraInputsManager.prototype.add = function (input) {
  34245. var type = input.getSimpleName();
  34246. if (this.attached[type]) {
  34247. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  34248. return;
  34249. }
  34250. this.attached[type] = input;
  34251. input.camera = this.camera;
  34252. //for checkInputs, we are dynamically creating a function
  34253. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  34254. if (input.checkInputs) {
  34255. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  34256. }
  34257. if (this.attachedElement) {
  34258. input.attachControl(this.attachedElement);
  34259. }
  34260. };
  34261. CameraInputsManager.prototype.remove = function (inputToRemove) {
  34262. for (var cam in this.attached) {
  34263. var input = this.attached[cam];
  34264. if (input === inputToRemove) {
  34265. input.detachControl(this.attachedElement);
  34266. input.camera = null;
  34267. delete this.attached[cam];
  34268. this.rebuildInputCheck();
  34269. }
  34270. }
  34271. };
  34272. CameraInputsManager.prototype.removeByType = function (inputType) {
  34273. for (var cam in this.attached) {
  34274. var input = this.attached[cam];
  34275. if (input.getClassName() === inputType) {
  34276. input.detachControl(this.attachedElement);
  34277. input.camera = null;
  34278. delete this.attached[cam];
  34279. this.rebuildInputCheck();
  34280. }
  34281. }
  34282. };
  34283. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  34284. var current = this.checkInputs;
  34285. return function () {
  34286. current();
  34287. fn();
  34288. };
  34289. };
  34290. CameraInputsManager.prototype.attachInput = function (input) {
  34291. input.attachControl(this.attachedElement, this.noPreventDefault);
  34292. };
  34293. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  34294. if (this.attachedElement) {
  34295. return;
  34296. }
  34297. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  34298. this.attachedElement = element;
  34299. this.noPreventDefault = noPreventDefault;
  34300. for (var cam in this.attached) {
  34301. var input = this.attached[cam];
  34302. this.attached[cam].attachControl(element, noPreventDefault);
  34303. }
  34304. };
  34305. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  34306. if (disconnect === void 0) { disconnect = false; }
  34307. if (this.attachedElement !== element) {
  34308. return;
  34309. }
  34310. for (var cam in this.attached) {
  34311. var input = this.attached[cam];
  34312. this.attached[cam].detachControl(element);
  34313. if (disconnect) {
  34314. this.attached[cam].camera = null;
  34315. }
  34316. }
  34317. this.attachedElement = null;
  34318. };
  34319. CameraInputsManager.prototype.rebuildInputCheck = function () {
  34320. this.checkInputs = function () { };
  34321. for (var cam in this.attached) {
  34322. var input = this.attached[cam];
  34323. if (input.checkInputs) {
  34324. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  34325. }
  34326. }
  34327. };
  34328. CameraInputsManager.prototype.clear = function () {
  34329. if (this.attachedElement) {
  34330. this.detachElement(this.attachedElement, true);
  34331. }
  34332. this.attached = {};
  34333. this.attachedElement = null;
  34334. this.checkInputs = function () { };
  34335. };
  34336. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  34337. var inputs = {};
  34338. for (var cam in this.attached) {
  34339. var input = this.attached[cam];
  34340. var res = BABYLON.SerializationHelper.Serialize(input);
  34341. inputs[input.getClassName()] = res;
  34342. }
  34343. serializedCamera.inputsmgr = inputs;
  34344. };
  34345. CameraInputsManager.prototype.parse = function (parsedCamera) {
  34346. var parsedInputs = parsedCamera.inputsmgr;
  34347. if (parsedInputs) {
  34348. this.clear();
  34349. for (var n in parsedInputs) {
  34350. var construct = BABYLON.CameraInputTypes[n];
  34351. if (construct) {
  34352. var parsedinput = parsedInputs[n];
  34353. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  34354. this.add(input);
  34355. }
  34356. }
  34357. }
  34358. else {
  34359. //2016-03-08 this part is for managing backward compatibility
  34360. for (var n in this.attached) {
  34361. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  34362. if (construct) {
  34363. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  34364. this.remove(this.attached[n]);
  34365. this.add(input);
  34366. }
  34367. }
  34368. }
  34369. };
  34370. return CameraInputsManager;
  34371. }());
  34372. BABYLON.CameraInputsManager = CameraInputsManager;
  34373. })(BABYLON || (BABYLON = {}));
  34374. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  34375. var BABYLON;
  34376. (function (BABYLON) {
  34377. var FreeCameraMouseInput = (function () {
  34378. function FreeCameraMouseInput(touchEnabled) {
  34379. if (touchEnabled === void 0) { touchEnabled = true; }
  34380. this.touchEnabled = touchEnabled;
  34381. this.buttons = [0, 1, 2];
  34382. this.angularSensibility = 2000.0;
  34383. }
  34384. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  34385. var _this = this;
  34386. var engine = this.camera.getEngine();
  34387. if (!this._pointerInput) {
  34388. this._pointerInput = function (p, s) {
  34389. var evt = p.event;
  34390. if (engine.isInVRExclusivePointerMode) {
  34391. return;
  34392. }
  34393. if (!_this.touchEnabled && evt.pointerType === "touch") {
  34394. return;
  34395. }
  34396. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  34397. return;
  34398. }
  34399. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  34400. try {
  34401. evt.srcElement.setPointerCapture(evt.pointerId);
  34402. }
  34403. catch (e) {
  34404. //Nothing to do with the error. Execution will continue.
  34405. }
  34406. _this.previousPosition = {
  34407. x: evt.clientX,
  34408. y: evt.clientY
  34409. };
  34410. if (!noPreventDefault) {
  34411. evt.preventDefault();
  34412. element.focus();
  34413. }
  34414. }
  34415. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  34416. try {
  34417. evt.srcElement.releasePointerCapture(evt.pointerId);
  34418. }
  34419. catch (e) {
  34420. //Nothing to do with the error.
  34421. }
  34422. _this.previousPosition = null;
  34423. if (!noPreventDefault) {
  34424. evt.preventDefault();
  34425. }
  34426. }
  34427. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  34428. if (!_this.previousPosition || engine.isPointerLock) {
  34429. return;
  34430. }
  34431. var offsetX = evt.clientX - _this.previousPosition.x;
  34432. var offsetY = evt.clientY - _this.previousPosition.y;
  34433. if (_this.camera.getScene().useRightHandedSystem) {
  34434. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  34435. }
  34436. else {
  34437. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  34438. }
  34439. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  34440. _this.previousPosition = {
  34441. x: evt.clientX,
  34442. y: evt.clientY
  34443. };
  34444. if (!noPreventDefault) {
  34445. evt.preventDefault();
  34446. }
  34447. }
  34448. };
  34449. }
  34450. this._onMouseMove = function (evt) {
  34451. if (!engine.isPointerLock) {
  34452. return;
  34453. }
  34454. if (engine.isInVRExclusivePointerMode) {
  34455. return;
  34456. }
  34457. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  34458. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  34459. if (_this.camera.getScene().useRightHandedSystem) {
  34460. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  34461. }
  34462. else {
  34463. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  34464. }
  34465. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  34466. _this.previousPosition = null;
  34467. if (!noPreventDefault) {
  34468. evt.preventDefault();
  34469. }
  34470. };
  34471. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  34472. element.addEventListener("mousemove", this._onMouseMove, false);
  34473. };
  34474. FreeCameraMouseInput.prototype.detachControl = function (element) {
  34475. if (this._observer && element) {
  34476. this.camera.getScene().onPointerObservable.remove(this._observer);
  34477. element.removeEventListener("mousemove", this._onMouseMove);
  34478. this._observer = null;
  34479. this._onMouseMove = null;
  34480. this.previousPosition = null;
  34481. }
  34482. };
  34483. FreeCameraMouseInput.prototype.getClassName = function () {
  34484. return "FreeCameraMouseInput";
  34485. };
  34486. FreeCameraMouseInput.prototype.getSimpleName = function () {
  34487. return "mouse";
  34488. };
  34489. return FreeCameraMouseInput;
  34490. }());
  34491. __decorate([
  34492. BABYLON.serialize()
  34493. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  34494. __decorate([
  34495. BABYLON.serialize()
  34496. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  34497. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  34498. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  34499. })(BABYLON || (BABYLON = {}));
  34500. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  34501. var BABYLON;
  34502. (function (BABYLON) {
  34503. var FreeCameraKeyboardMoveInput = (function () {
  34504. function FreeCameraKeyboardMoveInput() {
  34505. this._keys = [];
  34506. this.keysUp = [38];
  34507. this.keysDown = [40];
  34508. this.keysLeft = [37];
  34509. this.keysRight = [39];
  34510. }
  34511. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  34512. var _this = this;
  34513. if (this._onCanvasBlurObserver) {
  34514. return;
  34515. }
  34516. this._scene = this.camera.getScene();
  34517. this._engine = this._scene.getEngine();
  34518. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  34519. _this._keys = [];
  34520. });
  34521. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  34522. var evt = info.event;
  34523. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  34524. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34525. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34526. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34527. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34528. var index = _this._keys.indexOf(evt.keyCode);
  34529. if (index === -1) {
  34530. _this._keys.push(evt.keyCode);
  34531. }
  34532. if (!noPreventDefault) {
  34533. evt.preventDefault();
  34534. }
  34535. }
  34536. }
  34537. else {
  34538. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34539. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34540. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34541. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34542. var index = _this._keys.indexOf(evt.keyCode);
  34543. if (index >= 0) {
  34544. _this._keys.splice(index, 1);
  34545. }
  34546. if (!noPreventDefault) {
  34547. evt.preventDefault();
  34548. }
  34549. }
  34550. }
  34551. });
  34552. };
  34553. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  34554. if (this._scene) {
  34555. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  34556. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  34557. this._onKeyboardObserver = null;
  34558. this._onCanvasBlurObserver = null;
  34559. }
  34560. this._keys = [];
  34561. };
  34562. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  34563. if (this._onKeyboardObserver) {
  34564. var camera = this.camera;
  34565. // Keyboard
  34566. for (var index = 0; index < this._keys.length; index++) {
  34567. var keyCode = this._keys[index];
  34568. var speed = camera._computeLocalCameraSpeed();
  34569. if (this.keysLeft.indexOf(keyCode) !== -1) {
  34570. camera._localDirection.copyFromFloats(-speed, 0, 0);
  34571. }
  34572. else if (this.keysUp.indexOf(keyCode) !== -1) {
  34573. camera._localDirection.copyFromFloats(0, 0, speed);
  34574. }
  34575. else if (this.keysRight.indexOf(keyCode) !== -1) {
  34576. camera._localDirection.copyFromFloats(speed, 0, 0);
  34577. }
  34578. else if (this.keysDown.indexOf(keyCode) !== -1) {
  34579. camera._localDirection.copyFromFloats(0, 0, -speed);
  34580. }
  34581. if (camera.getScene().useRightHandedSystem) {
  34582. camera._localDirection.z *= -1;
  34583. }
  34584. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  34585. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  34586. camera.cameraDirection.addInPlace(camera._transformedDirection);
  34587. }
  34588. }
  34589. };
  34590. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  34591. return "FreeCameraKeyboardMoveInput";
  34592. };
  34593. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  34594. this._keys = [];
  34595. };
  34596. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  34597. return "keyboard";
  34598. };
  34599. return FreeCameraKeyboardMoveInput;
  34600. }());
  34601. __decorate([
  34602. BABYLON.serialize()
  34603. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  34604. __decorate([
  34605. BABYLON.serialize()
  34606. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  34607. __decorate([
  34608. BABYLON.serialize()
  34609. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  34610. __decorate([
  34611. BABYLON.serialize()
  34612. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  34613. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  34614. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  34615. })(BABYLON || (BABYLON = {}));
  34616. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  34617. var BABYLON;
  34618. (function (BABYLON) {
  34619. var FreeCameraInputsManager = (function (_super) {
  34620. __extends(FreeCameraInputsManager, _super);
  34621. function FreeCameraInputsManager(camera) {
  34622. return _super.call(this, camera) || this;
  34623. }
  34624. FreeCameraInputsManager.prototype.addKeyboard = function () {
  34625. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  34626. return this;
  34627. };
  34628. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  34629. if (touchEnabled === void 0) { touchEnabled = true; }
  34630. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  34631. return this;
  34632. };
  34633. FreeCameraInputsManager.prototype.addGamepad = function () {
  34634. this.add(new BABYLON.FreeCameraGamepadInput());
  34635. return this;
  34636. };
  34637. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  34638. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  34639. return this;
  34640. };
  34641. FreeCameraInputsManager.prototype.addTouch = function () {
  34642. this.add(new BABYLON.FreeCameraTouchInput());
  34643. return this;
  34644. };
  34645. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  34646. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  34647. return this;
  34648. };
  34649. return FreeCameraInputsManager;
  34650. }(BABYLON.CameraInputsManager));
  34651. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  34652. })(BABYLON || (BABYLON = {}));
  34653. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  34654. /// <reference path="babylon.camera.ts" />
  34655. var BABYLON;
  34656. (function (BABYLON) {
  34657. var TargetCamera = (function (_super) {
  34658. __extends(TargetCamera, _super);
  34659. function TargetCamera(name, position, scene) {
  34660. var _this = _super.call(this, name, position, scene) || this;
  34661. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34662. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  34663. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  34664. _this.speed = 2.0;
  34665. _this.noRotationConstraint = false;
  34666. _this.lockedTarget = null;
  34667. _this._currentTarget = BABYLON.Vector3.Zero();
  34668. _this._viewMatrix = BABYLON.Matrix.Zero();
  34669. _this._camMatrix = BABYLON.Matrix.Zero();
  34670. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  34671. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  34672. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  34673. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  34674. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  34675. _this._lookAtTemp = BABYLON.Matrix.Zero();
  34676. _this._tempMatrix = BABYLON.Matrix.Zero();
  34677. return _this;
  34678. }
  34679. TargetCamera.prototype.getFrontPosition = function (distance) {
  34680. var direction = this.getTarget().subtract(this.position);
  34681. direction.normalize();
  34682. direction.scaleInPlace(distance);
  34683. return this.globalPosition.add(direction);
  34684. };
  34685. TargetCamera.prototype._getLockedTargetPosition = function () {
  34686. if (!this.lockedTarget) {
  34687. return null;
  34688. }
  34689. if (this.lockedTarget.absolutePosition) {
  34690. this.lockedTarget.computeWorldMatrix();
  34691. }
  34692. return this.lockedTarget.absolutePosition || this.lockedTarget;
  34693. };
  34694. TargetCamera.prototype.storeState = function () {
  34695. this._storedPosition = this.position.clone();
  34696. this._storedRotation = this.rotation.clone();
  34697. if (this.rotationQuaternion) {
  34698. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  34699. }
  34700. return _super.prototype.storeState.call(this);
  34701. };
  34702. /**
  34703. * Restored camera state. You must call storeState() first
  34704. */
  34705. TargetCamera.prototype._restoreStateValues = function () {
  34706. if (!_super.prototype._restoreStateValues.call(this)) {
  34707. return false;
  34708. }
  34709. this.position = this._storedPosition.clone();
  34710. this.rotation = this._storedRotation.clone();
  34711. if (this.rotationQuaternion) {
  34712. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  34713. }
  34714. this.cameraDirection.copyFromFloats(0, 0, 0);
  34715. this.cameraRotation.copyFromFloats(0, 0);
  34716. return true;
  34717. };
  34718. // Cache
  34719. TargetCamera.prototype._initCache = function () {
  34720. _super.prototype._initCache.call(this);
  34721. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34722. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34723. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34724. };
  34725. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  34726. if (!ignoreParentClass) {
  34727. _super.prototype._updateCache.call(this);
  34728. }
  34729. var lockedTargetPosition = this._getLockedTargetPosition();
  34730. if (!lockedTargetPosition) {
  34731. this._cache.lockedTarget = null;
  34732. }
  34733. else {
  34734. if (!this._cache.lockedTarget) {
  34735. this._cache.lockedTarget = lockedTargetPosition.clone();
  34736. }
  34737. else {
  34738. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  34739. }
  34740. }
  34741. this._cache.rotation.copyFrom(this.rotation);
  34742. if (this.rotationQuaternion)
  34743. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34744. };
  34745. // Synchronized
  34746. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  34747. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  34748. return false;
  34749. }
  34750. var lockedTargetPosition = this._getLockedTargetPosition();
  34751. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  34752. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  34753. };
  34754. // Methods
  34755. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  34756. var engine = this.getEngine();
  34757. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  34758. };
  34759. // Target
  34760. TargetCamera.prototype.setTarget = function (target) {
  34761. this.upVector.normalize();
  34762. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  34763. this._camMatrix.invert();
  34764. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  34765. var vDir = target.subtract(this.position);
  34766. if (vDir.x >= 0.0) {
  34767. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  34768. }
  34769. else {
  34770. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  34771. }
  34772. this.rotation.z = 0;
  34773. if (isNaN(this.rotation.x)) {
  34774. this.rotation.x = 0;
  34775. }
  34776. if (isNaN(this.rotation.y)) {
  34777. this.rotation.y = 0;
  34778. }
  34779. if (isNaN(this.rotation.z)) {
  34780. this.rotation.z = 0;
  34781. }
  34782. if (this.rotationQuaternion) {
  34783. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34784. }
  34785. };
  34786. /**
  34787. * Return the current target position of the camera. This value is expressed in local space.
  34788. */
  34789. TargetCamera.prototype.getTarget = function () {
  34790. return this._currentTarget;
  34791. };
  34792. TargetCamera.prototype._decideIfNeedsToMove = function () {
  34793. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34794. };
  34795. TargetCamera.prototype._updatePosition = function () {
  34796. if (this.parent) {
  34797. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  34798. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  34799. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  34800. return;
  34801. }
  34802. this.position.addInPlace(this.cameraDirection);
  34803. };
  34804. TargetCamera.prototype._checkInputs = function () {
  34805. var needToMove = this._decideIfNeedsToMove();
  34806. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  34807. // Move
  34808. if (needToMove) {
  34809. this._updatePosition();
  34810. }
  34811. // Rotate
  34812. if (needToRotate) {
  34813. this.rotation.x += this.cameraRotation.x;
  34814. this.rotation.y += this.cameraRotation.y;
  34815. //rotate, if quaternion is set and rotation was used
  34816. if (this.rotationQuaternion) {
  34817. var len = this.rotation.lengthSquared();
  34818. if (len) {
  34819. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34820. }
  34821. }
  34822. if (!this.noRotationConstraint) {
  34823. var limit = (Math.PI / 2) * 0.95;
  34824. if (this.rotation.x > limit)
  34825. this.rotation.x = limit;
  34826. if (this.rotation.x < -limit)
  34827. this.rotation.x = -limit;
  34828. }
  34829. }
  34830. // Inertia
  34831. if (needToMove) {
  34832. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  34833. this.cameraDirection.x = 0;
  34834. }
  34835. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  34836. this.cameraDirection.y = 0;
  34837. }
  34838. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  34839. this.cameraDirection.z = 0;
  34840. }
  34841. this.cameraDirection.scaleInPlace(this.inertia);
  34842. }
  34843. if (needToRotate) {
  34844. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  34845. this.cameraRotation.x = 0;
  34846. }
  34847. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  34848. this.cameraRotation.y = 0;
  34849. }
  34850. this.cameraRotation.scaleInPlace(this.inertia);
  34851. }
  34852. _super.prototype._checkInputs.call(this);
  34853. };
  34854. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  34855. if (this.rotationQuaternion) {
  34856. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  34857. //update the up vector!
  34858. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  34859. }
  34860. else {
  34861. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  34862. }
  34863. };
  34864. TargetCamera.prototype._getViewMatrix = function () {
  34865. if (!this.lockedTarget) {
  34866. // Compute
  34867. this._updateCameraRotationMatrix();
  34868. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  34869. // Computing target and final matrix
  34870. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  34871. }
  34872. else {
  34873. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  34874. }
  34875. if (this.getScene().useRightHandedSystem) {
  34876. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34877. }
  34878. else {
  34879. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34880. }
  34881. return this._viewMatrix;
  34882. };
  34883. /**
  34884. * @override
  34885. * Override Camera.createRigCamera
  34886. */
  34887. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  34888. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  34889. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  34890. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  34891. if (!this.rotationQuaternion) {
  34892. this.rotationQuaternion = new BABYLON.Quaternion();
  34893. }
  34894. rigCamera._cameraRigParams = {};
  34895. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  34896. }
  34897. return rigCamera;
  34898. }
  34899. return null;
  34900. };
  34901. /**
  34902. * @override
  34903. * Override Camera._updateRigCameras
  34904. */
  34905. TargetCamera.prototype._updateRigCameras = function () {
  34906. var camLeft = this._rigCameras[0];
  34907. var camRight = this._rigCameras[1];
  34908. switch (this.cameraRigMode) {
  34909. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34910. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34911. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34912. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34913. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  34914. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  34915. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  34916. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  34917. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  34918. camLeft.setTarget(this.getTarget());
  34919. camRight.setTarget(this.getTarget());
  34920. break;
  34921. case BABYLON.Camera.RIG_MODE_VR:
  34922. if (camLeft.rotationQuaternion) {
  34923. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34924. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34925. }
  34926. else {
  34927. camLeft.rotation.copyFrom(this.rotation);
  34928. camRight.rotation.copyFrom(this.rotation);
  34929. }
  34930. camLeft.position.copyFrom(this.position);
  34931. camRight.position.copyFrom(this.position);
  34932. break;
  34933. }
  34934. _super.prototype._updateRigCameras.call(this);
  34935. };
  34936. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  34937. if (!this._rigCamTransformMatrix) {
  34938. this._rigCamTransformMatrix = new BABYLON.Matrix();
  34939. }
  34940. var target = this.getTarget();
  34941. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  34942. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  34943. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  34944. };
  34945. TargetCamera.prototype.getClassName = function () {
  34946. return "TargetCamera";
  34947. };
  34948. return TargetCamera;
  34949. }(BABYLON.Camera));
  34950. __decorate([
  34951. BABYLON.serializeAsVector3()
  34952. ], TargetCamera.prototype, "rotation", void 0);
  34953. __decorate([
  34954. BABYLON.serialize()
  34955. ], TargetCamera.prototype, "speed", void 0);
  34956. __decorate([
  34957. BABYLON.serializeAsMeshReference("lockedTargetId")
  34958. ], TargetCamera.prototype, "lockedTarget", void 0);
  34959. BABYLON.TargetCamera = TargetCamera;
  34960. })(BABYLON || (BABYLON = {}));
  34961. //# sourceMappingURL=babylon.targetCamera.js.map
  34962. var BABYLON;
  34963. (function (BABYLON) {
  34964. var FreeCamera = (function (_super) {
  34965. __extends(FreeCamera, _super);
  34966. function FreeCamera(name, position, scene) {
  34967. var _this = _super.call(this, name, position, scene) || this;
  34968. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  34969. _this.checkCollisions = false;
  34970. _this.applyGravity = false;
  34971. _this._needMoveForGravity = false;
  34972. _this._oldPosition = BABYLON.Vector3.Zero();
  34973. _this._diffPosition = BABYLON.Vector3.Zero();
  34974. _this._newPosition = BABYLON.Vector3.Zero();
  34975. // Collisions
  34976. _this._collisionMask = -1;
  34977. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  34978. if (collidedMesh === void 0) { collidedMesh = null; }
  34979. //TODO move this to the collision coordinator!
  34980. if (_this.getScene().workerCollisions)
  34981. newPosition.multiplyInPlace(_this._collider.radius);
  34982. var updatePosition = function (newPos) {
  34983. _this._newPosition.copyFrom(newPos);
  34984. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  34985. var oldPosition = _this.position.clone();
  34986. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  34987. _this.position.addInPlace(_this._diffPosition);
  34988. if (_this.onCollide && collidedMesh) {
  34989. _this.onCollide(collidedMesh);
  34990. }
  34991. }
  34992. };
  34993. updatePosition(newPosition);
  34994. };
  34995. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  34996. _this.inputs.addKeyboard().addMouse();
  34997. return _this;
  34998. }
  34999. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  35000. //-- begin properties for backward compatibility for inputs
  35001. get: function () {
  35002. var mouse = this.inputs.attached["mouse"];
  35003. if (mouse)
  35004. return mouse.angularSensibility;
  35005. },
  35006. set: function (value) {
  35007. var mouse = this.inputs.attached["mouse"];
  35008. if (mouse)
  35009. mouse.angularSensibility = value;
  35010. },
  35011. enumerable: true,
  35012. configurable: true
  35013. });
  35014. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  35015. get: function () {
  35016. var keyboard = this.inputs.attached["keyboard"];
  35017. if (keyboard)
  35018. return keyboard.keysUp;
  35019. },
  35020. set: function (value) {
  35021. var keyboard = this.inputs.attached["keyboard"];
  35022. if (keyboard)
  35023. keyboard.keysUp = value;
  35024. },
  35025. enumerable: true,
  35026. configurable: true
  35027. });
  35028. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  35029. get: function () {
  35030. var keyboard = this.inputs.attached["keyboard"];
  35031. if (keyboard)
  35032. return keyboard.keysDown;
  35033. },
  35034. set: function (value) {
  35035. var keyboard = this.inputs.attached["keyboard"];
  35036. if (keyboard)
  35037. keyboard.keysDown = value;
  35038. },
  35039. enumerable: true,
  35040. configurable: true
  35041. });
  35042. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  35043. get: function () {
  35044. var keyboard = this.inputs.attached["keyboard"];
  35045. if (keyboard)
  35046. return keyboard.keysLeft;
  35047. },
  35048. set: function (value) {
  35049. var keyboard = this.inputs.attached["keyboard"];
  35050. if (keyboard)
  35051. keyboard.keysLeft = value;
  35052. },
  35053. enumerable: true,
  35054. configurable: true
  35055. });
  35056. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  35057. get: function () {
  35058. var keyboard = this.inputs.attached["keyboard"];
  35059. if (keyboard)
  35060. return keyboard.keysRight;
  35061. },
  35062. set: function (value) {
  35063. var keyboard = this.inputs.attached["keyboard"];
  35064. if (keyboard)
  35065. keyboard.keysRight = value;
  35066. },
  35067. enumerable: true,
  35068. configurable: true
  35069. });
  35070. // Controls
  35071. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  35072. this.inputs.attachElement(element, noPreventDefault);
  35073. };
  35074. FreeCamera.prototype.detachControl = function (element) {
  35075. this.inputs.detachElement(element);
  35076. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  35077. this.cameraRotation = new BABYLON.Vector2(0, 0);
  35078. };
  35079. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  35080. get: function () {
  35081. return this._collisionMask;
  35082. },
  35083. set: function (mask) {
  35084. this._collisionMask = !isNaN(mask) ? mask : -1;
  35085. },
  35086. enumerable: true,
  35087. configurable: true
  35088. });
  35089. FreeCamera.prototype._collideWithWorld = function (displacement) {
  35090. var globalPosition;
  35091. if (this.parent) {
  35092. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  35093. }
  35094. else {
  35095. globalPosition = this.position;
  35096. }
  35097. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  35098. if (!this._collider) {
  35099. this._collider = new BABYLON.Collider();
  35100. }
  35101. this._collider.radius = this.ellipsoid;
  35102. this._collider.collisionMask = this._collisionMask;
  35103. //no need for clone, as long as gravity is not on.
  35104. var actualDisplacement = displacement;
  35105. //add gravity to the direction to prevent the dual-collision checking
  35106. if (this.applyGravity) {
  35107. //this prevents mending with cameraDirection, a global variable of the free camera class.
  35108. actualDisplacement = displacement.add(this.getScene().gravity);
  35109. }
  35110. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  35111. };
  35112. FreeCamera.prototype._checkInputs = function () {
  35113. if (!this._localDirection) {
  35114. this._localDirection = BABYLON.Vector3.Zero();
  35115. this._transformedDirection = BABYLON.Vector3.Zero();
  35116. }
  35117. this.inputs.checkInputs();
  35118. _super.prototype._checkInputs.call(this);
  35119. };
  35120. FreeCamera.prototype._decideIfNeedsToMove = function () {
  35121. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  35122. };
  35123. FreeCamera.prototype._updatePosition = function () {
  35124. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  35125. this._collideWithWorld(this.cameraDirection);
  35126. }
  35127. else {
  35128. _super.prototype._updatePosition.call(this);
  35129. }
  35130. };
  35131. FreeCamera.prototype.dispose = function () {
  35132. this.inputs.clear();
  35133. _super.prototype.dispose.call(this);
  35134. };
  35135. FreeCamera.prototype.getClassName = function () {
  35136. return "FreeCamera";
  35137. };
  35138. return FreeCamera;
  35139. }(BABYLON.TargetCamera));
  35140. __decorate([
  35141. BABYLON.serializeAsVector3()
  35142. ], FreeCamera.prototype, "ellipsoid", void 0);
  35143. __decorate([
  35144. BABYLON.serialize()
  35145. ], FreeCamera.prototype, "checkCollisions", void 0);
  35146. __decorate([
  35147. BABYLON.serialize()
  35148. ], FreeCamera.prototype, "applyGravity", void 0);
  35149. BABYLON.FreeCamera = FreeCamera;
  35150. })(BABYLON || (BABYLON = {}));
  35151. //# sourceMappingURL=babylon.freeCamera.js.map
  35152. var BABYLON;
  35153. (function (BABYLON) {
  35154. var ArcRotateCameraKeyboardMoveInput = (function () {
  35155. function ArcRotateCameraKeyboardMoveInput() {
  35156. this._keys = [];
  35157. this.keysUp = [38];
  35158. this.keysDown = [40];
  35159. this.keysLeft = [37];
  35160. this.keysRight = [39];
  35161. this.keysReset = [220];
  35162. this.panningSensibility = 50.0;
  35163. this.zoomingSensibility = 25.0;
  35164. this.useAltToZoom = true;
  35165. }
  35166. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  35167. var _this = this;
  35168. if (this._onCanvasBlurObserver) {
  35169. return;
  35170. }
  35171. this._scene = this.camera.getScene();
  35172. this._engine = this._scene.getEngine();
  35173. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  35174. _this._keys = [];
  35175. });
  35176. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  35177. var evt = info.event;
  35178. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  35179. _this._ctrlPressed = evt.ctrlKey;
  35180. _this._altPressed = evt.altKey;
  35181. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  35182. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  35183. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  35184. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  35185. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  35186. var index = _this._keys.indexOf(evt.keyCode);
  35187. if (index === -1) {
  35188. _this._keys.push(evt.keyCode);
  35189. }
  35190. if (evt.preventDefault) {
  35191. if (!noPreventDefault) {
  35192. evt.preventDefault();
  35193. }
  35194. }
  35195. }
  35196. }
  35197. else {
  35198. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  35199. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  35200. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  35201. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  35202. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  35203. var index = _this._keys.indexOf(evt.keyCode);
  35204. if (index >= 0) {
  35205. _this._keys.splice(index, 1);
  35206. }
  35207. if (evt.preventDefault) {
  35208. if (!noPreventDefault) {
  35209. evt.preventDefault();
  35210. }
  35211. }
  35212. }
  35213. }
  35214. });
  35215. };
  35216. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  35217. if (this._scene) {
  35218. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  35219. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  35220. this._onKeyboardObserver = null;
  35221. this._onCanvasBlurObserver = null;
  35222. }
  35223. this._keys = [];
  35224. };
  35225. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  35226. if (this._onKeyboardObserver) {
  35227. var camera = this.camera;
  35228. for (var index = 0; index < this._keys.length; index++) {
  35229. var keyCode = this._keys[index];
  35230. if (this.keysLeft.indexOf(keyCode) !== -1) {
  35231. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35232. camera.inertialPanningX -= 1 / this.panningSensibility;
  35233. }
  35234. else {
  35235. camera.inertialAlphaOffset -= 0.01;
  35236. }
  35237. }
  35238. else if (this.keysUp.indexOf(keyCode) !== -1) {
  35239. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35240. camera.inertialPanningY += 1 / this.panningSensibility;
  35241. }
  35242. else if (this._altPressed && this.useAltToZoom) {
  35243. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  35244. }
  35245. else {
  35246. camera.inertialBetaOffset -= 0.01;
  35247. }
  35248. }
  35249. else if (this.keysRight.indexOf(keyCode) !== -1) {
  35250. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35251. camera.inertialPanningX += 1 / this.panningSensibility;
  35252. }
  35253. else {
  35254. camera.inertialAlphaOffset += 0.01;
  35255. }
  35256. }
  35257. else if (this.keysDown.indexOf(keyCode) !== -1) {
  35258. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35259. camera.inertialPanningY -= 1 / this.panningSensibility;
  35260. }
  35261. else if (this._altPressed && this.useAltToZoom) {
  35262. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  35263. }
  35264. else {
  35265. camera.inertialBetaOffset += 0.01;
  35266. }
  35267. }
  35268. else if (this.keysReset.indexOf(keyCode) !== -1) {
  35269. camera.restoreState();
  35270. }
  35271. }
  35272. }
  35273. };
  35274. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  35275. return "ArcRotateCameraKeyboardMoveInput";
  35276. };
  35277. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  35278. return "keyboard";
  35279. };
  35280. return ArcRotateCameraKeyboardMoveInput;
  35281. }());
  35282. __decorate([
  35283. BABYLON.serialize()
  35284. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  35285. __decorate([
  35286. BABYLON.serialize()
  35287. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  35288. __decorate([
  35289. BABYLON.serialize()
  35290. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  35291. __decorate([
  35292. BABYLON.serialize()
  35293. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  35294. __decorate([
  35295. BABYLON.serialize()
  35296. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  35297. __decorate([
  35298. BABYLON.serialize()
  35299. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  35300. __decorate([
  35301. BABYLON.serialize()
  35302. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  35303. __decorate([
  35304. BABYLON.serialize()
  35305. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  35306. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  35307. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  35308. })(BABYLON || (BABYLON = {}));
  35309. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  35310. var BABYLON;
  35311. (function (BABYLON) {
  35312. var ArcRotateCameraMouseWheelInput = (function () {
  35313. function ArcRotateCameraMouseWheelInput() {
  35314. this.wheelPrecision = 3.0;
  35315. }
  35316. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  35317. var _this = this;
  35318. this._wheel = function (p, s) {
  35319. //sanity check - this should be a PointerWheel event.
  35320. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  35321. return;
  35322. var event = p.event;
  35323. var delta = 0;
  35324. if (event.wheelDelta) {
  35325. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  35326. }
  35327. else if (event.detail) {
  35328. delta = -event.detail / _this.wheelPrecision;
  35329. }
  35330. if (delta)
  35331. _this.camera.inertialRadiusOffset += delta;
  35332. if (event.preventDefault) {
  35333. if (!noPreventDefault) {
  35334. event.preventDefault();
  35335. }
  35336. }
  35337. };
  35338. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  35339. };
  35340. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  35341. if (this._observer && element) {
  35342. this.camera.getScene().onPointerObservable.remove(this._observer);
  35343. this._observer = null;
  35344. this._wheel = null;
  35345. }
  35346. };
  35347. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  35348. return "ArcRotateCameraMouseWheelInput";
  35349. };
  35350. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  35351. return "mousewheel";
  35352. };
  35353. return ArcRotateCameraMouseWheelInput;
  35354. }());
  35355. __decorate([
  35356. BABYLON.serialize()
  35357. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  35358. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  35359. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  35360. })(BABYLON || (BABYLON = {}));
  35361. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  35362. var BABYLON;
  35363. (function (BABYLON) {
  35364. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  35365. var ArcRotateCameraPointersInput = (function () {
  35366. function ArcRotateCameraPointersInput() {
  35367. this.buttons = [0, 1, 2];
  35368. this.angularSensibilityX = 1000.0;
  35369. this.angularSensibilityY = 1000.0;
  35370. this.pinchPrecision = 12.0;
  35371. this.panningSensibility = 1000.0;
  35372. this.multiTouchPanning = true;
  35373. this.multiTouchPanAndZoom = true;
  35374. this._isPanClick = false;
  35375. this.pinchInwards = true;
  35376. }
  35377. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  35378. var _this = this;
  35379. var engine = this.camera.getEngine();
  35380. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  35381. var pointA, pointB;
  35382. var previousPinchSquaredDistance = 0;
  35383. var initialDistance = 0;
  35384. var twoFingerActivityCount = 0;
  35385. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  35386. this._pointerInput = function (p, s) {
  35387. var evt = p.event;
  35388. if (engine.isInVRExclusivePointerMode) {
  35389. return;
  35390. }
  35391. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  35392. return;
  35393. }
  35394. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  35395. try {
  35396. evt.srcElement.setPointerCapture(evt.pointerId);
  35397. }
  35398. catch (e) {
  35399. //Nothing to do with the error. Execution will continue.
  35400. }
  35401. // Manage panning with pan button click
  35402. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  35403. // manage pointers
  35404. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  35405. if (pointA === undefined) {
  35406. pointA = cacheSoloPointer;
  35407. }
  35408. else if (pointB === undefined) {
  35409. pointB = cacheSoloPointer;
  35410. }
  35411. if (!noPreventDefault) {
  35412. evt.preventDefault();
  35413. element.focus();
  35414. }
  35415. }
  35416. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  35417. _this.camera.restoreState();
  35418. }
  35419. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  35420. try {
  35421. evt.srcElement.releasePointerCapture(evt.pointerId);
  35422. }
  35423. catch (e) {
  35424. //Nothing to do with the error.
  35425. }
  35426. cacheSoloPointer = null;
  35427. previousPinchSquaredDistance = 0;
  35428. previousMultiTouchPanPosition.isPaning = false;
  35429. previousMultiTouchPanPosition.isPinching = false;
  35430. twoFingerActivityCount = 0;
  35431. initialDistance = 0;
  35432. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  35433. //but emptying completly pointers collection is required to fix a bug on iPhone :
  35434. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  35435. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  35436. if (engine.badOS) {
  35437. pointA = pointB = undefined;
  35438. }
  35439. else {
  35440. //only remove the impacted pointer in case of multitouch allowing on most
  35441. //platforms switching from rotate to zoom and pan seamlessly.
  35442. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  35443. pointA = pointB;
  35444. pointB = undefined;
  35445. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  35446. }
  35447. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  35448. pointB = undefined;
  35449. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  35450. }
  35451. else {
  35452. pointA = pointB = undefined;
  35453. }
  35454. }
  35455. if (!noPreventDefault) {
  35456. evt.preventDefault();
  35457. }
  35458. }
  35459. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  35460. if (!noPreventDefault) {
  35461. evt.preventDefault();
  35462. }
  35463. // One button down
  35464. if (pointA && pointB === undefined) {
  35465. if (_this.panningSensibility !== 0 &&
  35466. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  35467. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  35468. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  35469. }
  35470. else {
  35471. var offsetX = evt.clientX - cacheSoloPointer.x;
  35472. var offsetY = evt.clientY - cacheSoloPointer.y;
  35473. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  35474. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  35475. }
  35476. cacheSoloPointer.x = evt.clientX;
  35477. cacheSoloPointer.y = evt.clientY;
  35478. }
  35479. else if (pointA && pointB) {
  35480. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  35481. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  35482. ed.x = evt.clientX;
  35483. ed.y = evt.clientY;
  35484. var direction = _this.pinchInwards ? 1 : -1;
  35485. var distX = pointA.x - pointB.x;
  35486. var distY = pointA.y - pointB.y;
  35487. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  35488. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  35489. if (previousPinchSquaredDistance === 0) {
  35490. initialDistance = pinchDistance;
  35491. previousPinchSquaredDistance = pinchSquaredDistance;
  35492. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  35493. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  35494. return;
  35495. }
  35496. if (_this.multiTouchPanAndZoom) {
  35497. _this.camera
  35498. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  35499. (_this.pinchPrecision *
  35500. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  35501. direction);
  35502. if (_this.panningSensibility !== 0) {
  35503. var pointersCenterX = (pointA.x + pointB.x) / 2;
  35504. var pointersCenterY = (pointA.y + pointB.y) / 2;
  35505. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  35506. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  35507. previousMultiTouchPanPosition.x = pointersCenterX;
  35508. previousMultiTouchPanPosition.y = pointersCenterY;
  35509. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  35510. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  35511. }
  35512. }
  35513. else {
  35514. twoFingerActivityCount++;
  35515. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  35516. _this.camera
  35517. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  35518. (_this.pinchPrecision *
  35519. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  35520. direction);
  35521. previousMultiTouchPanPosition.isPaning = false;
  35522. previousMultiTouchPanPosition.isPinching = true;
  35523. }
  35524. else {
  35525. if (cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  35526. if (!previousMultiTouchPanPosition.isPaning) {
  35527. previousMultiTouchPanPosition.isPaning = true;
  35528. previousMultiTouchPanPosition.isPinching = false;
  35529. previousMultiTouchPanPosition.x = ed.x;
  35530. previousMultiTouchPanPosition.y = ed.y;
  35531. return;
  35532. }
  35533. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  35534. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  35535. }
  35536. }
  35537. if (cacheSoloPointer.pointerId === evt.pointerId) {
  35538. previousMultiTouchPanPosition.x = ed.x;
  35539. previousMultiTouchPanPosition.y = ed.y;
  35540. }
  35541. }
  35542. previousPinchSquaredDistance = pinchSquaredDistance;
  35543. }
  35544. }
  35545. };
  35546. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  35547. this._onContextMenu = function (evt) {
  35548. evt.preventDefault();
  35549. };
  35550. if (!this.camera._useCtrlForPanning) {
  35551. element.addEventListener("contextmenu", this._onContextMenu, false);
  35552. }
  35553. this._onLostFocus = function () {
  35554. //this._keys = [];
  35555. pointA = pointB = undefined;
  35556. previousPinchSquaredDistance = 0;
  35557. previousMultiTouchPanPosition.isPaning = false;
  35558. previousMultiTouchPanPosition.isPinching = false;
  35559. twoFingerActivityCount = 0;
  35560. cacheSoloPointer = null;
  35561. initialDistance = 0;
  35562. };
  35563. this._onMouseMove = function (evt) {
  35564. if (!engine.isPointerLock) {
  35565. return;
  35566. }
  35567. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  35568. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  35569. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  35570. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  35571. if (!noPreventDefault) {
  35572. evt.preventDefault();
  35573. }
  35574. };
  35575. this._onGestureStart = function (e) {
  35576. if (window.MSGesture === undefined) {
  35577. return;
  35578. }
  35579. if (!_this._MSGestureHandler) {
  35580. _this._MSGestureHandler = new MSGesture();
  35581. _this._MSGestureHandler.target = element;
  35582. }
  35583. _this._MSGestureHandler.addPointer(e.pointerId);
  35584. };
  35585. this._onGesture = function (e) {
  35586. _this.camera.radius *= e.scale;
  35587. if (e.preventDefault) {
  35588. if (!noPreventDefault) {
  35589. e.stopPropagation();
  35590. e.preventDefault();
  35591. }
  35592. }
  35593. };
  35594. element.addEventListener("mousemove", this._onMouseMove, false);
  35595. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  35596. element.addEventListener("MSGestureChange", this._onGesture, false);
  35597. BABYLON.Tools.RegisterTopRootEvents([
  35598. { name: "blur", handler: this._onLostFocus }
  35599. ]);
  35600. };
  35601. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  35602. BABYLON.Tools.UnregisterTopRootEvents([
  35603. { name: "blur", handler: this._onLostFocus }
  35604. ]);
  35605. if (element && this._observer) {
  35606. this.camera.getScene().onPointerObservable.remove(this._observer);
  35607. this._observer = null;
  35608. element.removeEventListener("contextmenu", this._onContextMenu);
  35609. element.removeEventListener("mousemove", this._onMouseMove);
  35610. element.removeEventListener("MSPointerDown", this._onGestureStart);
  35611. element.removeEventListener("MSGestureChange", this._onGesture);
  35612. this._isPanClick = false;
  35613. this.pinchInwards = true;
  35614. this._onMouseMove = null;
  35615. this._onGestureStart = null;
  35616. this._onGesture = null;
  35617. this._MSGestureHandler = null;
  35618. this._onLostFocus = null;
  35619. this._onContextMenu = null;
  35620. }
  35621. };
  35622. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  35623. return "ArcRotateCameraPointersInput";
  35624. };
  35625. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  35626. return "pointers";
  35627. };
  35628. return ArcRotateCameraPointersInput;
  35629. }());
  35630. __decorate([
  35631. BABYLON.serialize()
  35632. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  35633. __decorate([
  35634. BABYLON.serialize()
  35635. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  35636. __decorate([
  35637. BABYLON.serialize()
  35638. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  35639. __decorate([
  35640. BABYLON.serialize()
  35641. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  35642. __decorate([
  35643. BABYLON.serialize()
  35644. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  35645. __decorate([
  35646. BABYLON.serialize()
  35647. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  35648. __decorate([
  35649. BABYLON.serialize()
  35650. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  35651. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  35652. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  35653. })(BABYLON || (BABYLON = {}));
  35654. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  35655. /// <reference path="babylon.targetCamera.ts" />
  35656. /// <reference path="..\Tools\babylon.tools.ts" />
  35657. var BABYLON;
  35658. (function (BABYLON) {
  35659. var ArcRotateCamera = (function (_super) {
  35660. __extends(ArcRotateCamera, _super);
  35661. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  35662. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  35663. _this.inertialAlphaOffset = 0;
  35664. _this.inertialBetaOffset = 0;
  35665. _this.inertialRadiusOffset = 0;
  35666. _this.lowerAlphaLimit = null;
  35667. _this.upperAlphaLimit = null;
  35668. _this.lowerBetaLimit = 0.01;
  35669. _this.upperBetaLimit = Math.PI;
  35670. _this.lowerRadiusLimit = null;
  35671. _this.upperRadiusLimit = null;
  35672. _this.inertialPanningX = 0;
  35673. _this.inertialPanningY = 0;
  35674. _this.pinchToPanMaxDistance = 20;
  35675. _this.panningDistanceLimit = null;
  35676. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  35677. _this.panningInertia = 0.9;
  35678. //-- end properties for backward compatibility for inputs
  35679. _this.zoomOnFactor = 1;
  35680. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  35681. _this.allowUpsideDown = true;
  35682. _this._viewMatrix = new BABYLON.Matrix();
  35683. // Panning
  35684. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  35685. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  35686. _this.checkCollisions = false;
  35687. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  35688. _this._previousPosition = BABYLON.Vector3.Zero();
  35689. _this._collisionVelocity = BABYLON.Vector3.Zero();
  35690. _this._newPosition = BABYLON.Vector3.Zero();
  35691. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  35692. if (collidedMesh === void 0) { collidedMesh = null; }
  35693. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  35694. newPosition.multiplyInPlace(_this._collider.radius);
  35695. }
  35696. if (!collidedMesh) {
  35697. _this._previousPosition.copyFrom(_this.position);
  35698. }
  35699. else {
  35700. _this.setPosition(newPosition);
  35701. if (_this.onCollide) {
  35702. _this.onCollide(collidedMesh);
  35703. }
  35704. }
  35705. // Recompute because of constraints
  35706. var cosa = Math.cos(_this.alpha);
  35707. var sina = Math.sin(_this.alpha);
  35708. var cosb = Math.cos(_this.beta);
  35709. var sinb = Math.sin(_this.beta);
  35710. if (sinb === 0) {
  35711. sinb = 0.0001;
  35712. }
  35713. var target = _this._getTargetPosition();
  35714. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  35715. _this.position.copyFrom(_this._newPosition);
  35716. var up = _this.upVector;
  35717. if (_this.allowUpsideDown && _this.beta < 0) {
  35718. up = up.clone();
  35719. up = up.negate();
  35720. }
  35721. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  35722. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  35723. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  35724. _this._collisionTriggered = false;
  35725. };
  35726. _this._target = BABYLON.Vector3.Zero();
  35727. if (target) {
  35728. _this.setTarget(target);
  35729. }
  35730. _this.alpha = alpha;
  35731. _this.beta = beta;
  35732. _this.radius = radius;
  35733. _this.getViewMatrix();
  35734. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  35735. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  35736. return _this;
  35737. }
  35738. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  35739. get: function () {
  35740. return this._target;
  35741. },
  35742. set: function (value) {
  35743. this.setTarget(value);
  35744. },
  35745. enumerable: true,
  35746. configurable: true
  35747. });
  35748. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  35749. //-- begin properties for backward compatibility for inputs
  35750. get: function () {
  35751. var pointers = this.inputs.attached["pointers"];
  35752. if (pointers)
  35753. return pointers.angularSensibilityX;
  35754. },
  35755. set: function (value) {
  35756. var pointers = this.inputs.attached["pointers"];
  35757. if (pointers) {
  35758. pointers.angularSensibilityX = value;
  35759. }
  35760. },
  35761. enumerable: true,
  35762. configurable: true
  35763. });
  35764. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  35765. get: function () {
  35766. var pointers = this.inputs.attached["pointers"];
  35767. if (pointers)
  35768. return pointers.angularSensibilityY;
  35769. },
  35770. set: function (value) {
  35771. var pointers = this.inputs.attached["pointers"];
  35772. if (pointers) {
  35773. pointers.angularSensibilityY = value;
  35774. }
  35775. },
  35776. enumerable: true,
  35777. configurable: true
  35778. });
  35779. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  35780. get: function () {
  35781. var pointers = this.inputs.attached["pointers"];
  35782. if (pointers)
  35783. return pointers.pinchPrecision;
  35784. },
  35785. set: function (value) {
  35786. var pointers = this.inputs.attached["pointers"];
  35787. if (pointers) {
  35788. pointers.pinchPrecision = value;
  35789. }
  35790. },
  35791. enumerable: true,
  35792. configurable: true
  35793. });
  35794. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  35795. get: function () {
  35796. var pointers = this.inputs.attached["pointers"];
  35797. if (pointers)
  35798. return pointers.panningSensibility;
  35799. },
  35800. set: function (value) {
  35801. var pointers = this.inputs.attached["pointers"];
  35802. if (pointers) {
  35803. pointers.panningSensibility = value;
  35804. }
  35805. },
  35806. enumerable: true,
  35807. configurable: true
  35808. });
  35809. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  35810. get: function () {
  35811. var keyboard = this.inputs.attached["keyboard"];
  35812. if (keyboard)
  35813. return keyboard.keysUp;
  35814. },
  35815. set: function (value) {
  35816. var keyboard = this.inputs.attached["keyboard"];
  35817. if (keyboard)
  35818. keyboard.keysUp = value;
  35819. },
  35820. enumerable: true,
  35821. configurable: true
  35822. });
  35823. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  35824. get: function () {
  35825. var keyboard = this.inputs.attached["keyboard"];
  35826. if (keyboard)
  35827. return keyboard.keysDown;
  35828. },
  35829. set: function (value) {
  35830. var keyboard = this.inputs.attached["keyboard"];
  35831. if (keyboard)
  35832. keyboard.keysDown = value;
  35833. },
  35834. enumerable: true,
  35835. configurable: true
  35836. });
  35837. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  35838. get: function () {
  35839. var keyboard = this.inputs.attached["keyboard"];
  35840. if (keyboard)
  35841. return keyboard.keysLeft;
  35842. },
  35843. set: function (value) {
  35844. var keyboard = this.inputs.attached["keyboard"];
  35845. if (keyboard)
  35846. keyboard.keysLeft = value;
  35847. },
  35848. enumerable: true,
  35849. configurable: true
  35850. });
  35851. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  35852. get: function () {
  35853. var keyboard = this.inputs.attached["keyboard"];
  35854. if (keyboard)
  35855. return keyboard.keysRight;
  35856. },
  35857. set: function (value) {
  35858. var keyboard = this.inputs.attached["keyboard"];
  35859. if (keyboard)
  35860. keyboard.keysRight = value;
  35861. },
  35862. enumerable: true,
  35863. configurable: true
  35864. });
  35865. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  35866. get: function () {
  35867. var mousewheel = this.inputs.attached["mousewheel"];
  35868. if (mousewheel)
  35869. return mousewheel.wheelPrecision;
  35870. },
  35871. set: function (value) {
  35872. var mousewheel = this.inputs.attached["mousewheel"];
  35873. if (mousewheel)
  35874. mousewheel.wheelPrecision = value;
  35875. },
  35876. enumerable: true,
  35877. configurable: true
  35878. });
  35879. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  35880. get: function () {
  35881. return this._bouncingBehavior;
  35882. },
  35883. enumerable: true,
  35884. configurable: true
  35885. });
  35886. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  35887. get: function () {
  35888. return this._bouncingBehavior != null;
  35889. },
  35890. set: function (value) {
  35891. if (value === this.useBouncingBehavior) {
  35892. return;
  35893. }
  35894. if (value) {
  35895. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  35896. this.addBehavior(this._bouncingBehavior);
  35897. }
  35898. else {
  35899. this.removeBehavior(this._bouncingBehavior);
  35900. this._bouncingBehavior = null;
  35901. }
  35902. },
  35903. enumerable: true,
  35904. configurable: true
  35905. });
  35906. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  35907. get: function () {
  35908. return this._framingBehavior;
  35909. },
  35910. enumerable: true,
  35911. configurable: true
  35912. });
  35913. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  35914. get: function () {
  35915. return this._framingBehavior != null;
  35916. },
  35917. set: function (value) {
  35918. if (value === this.useFramingBehavior) {
  35919. return;
  35920. }
  35921. if (value) {
  35922. this._framingBehavior = new BABYLON.FramingBehavior();
  35923. this.addBehavior(this._framingBehavior);
  35924. }
  35925. else {
  35926. this.removeBehavior(this._framingBehavior);
  35927. this._framingBehavior = null;
  35928. }
  35929. },
  35930. enumerable: true,
  35931. configurable: true
  35932. });
  35933. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  35934. get: function () {
  35935. return this._autoRotationBehavior;
  35936. },
  35937. enumerable: true,
  35938. configurable: true
  35939. });
  35940. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  35941. get: function () {
  35942. return this._autoRotationBehavior != null;
  35943. },
  35944. set: function (value) {
  35945. if (value === this.useAutoRotationBehavior) {
  35946. return;
  35947. }
  35948. if (value) {
  35949. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  35950. this.addBehavior(this._autoRotationBehavior);
  35951. }
  35952. else {
  35953. this.removeBehavior(this._autoRotationBehavior);
  35954. this._autoRotationBehavior = null;
  35955. }
  35956. },
  35957. enumerable: true,
  35958. configurable: true
  35959. });
  35960. // Cache
  35961. ArcRotateCamera.prototype._initCache = function () {
  35962. _super.prototype._initCache.call(this);
  35963. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  35964. this._cache.alpha = undefined;
  35965. this._cache.beta = undefined;
  35966. this._cache.radius = undefined;
  35967. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  35968. };
  35969. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  35970. if (!ignoreParentClass) {
  35971. _super.prototype._updateCache.call(this);
  35972. }
  35973. this._cache._target.copyFrom(this._getTargetPosition());
  35974. this._cache.alpha = this.alpha;
  35975. this._cache.beta = this.beta;
  35976. this._cache.radius = this.radius;
  35977. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  35978. };
  35979. ArcRotateCamera.prototype._getTargetPosition = function () {
  35980. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  35981. var pos = this._targetHost.getAbsolutePosition();
  35982. if (this._targetBoundingCenter) {
  35983. pos.addToRef(this._targetBoundingCenter, this._target);
  35984. }
  35985. else {
  35986. this._target.copyFrom(pos);
  35987. }
  35988. }
  35989. var lockedTargetPosition = this._getLockedTargetPosition();
  35990. if (lockedTargetPosition) {
  35991. return lockedTargetPosition;
  35992. }
  35993. return this._target;
  35994. };
  35995. ArcRotateCamera.prototype.storeState = function () {
  35996. this._storedAlpha = this.alpha;
  35997. this._storedBeta = this.beta;
  35998. this._storedRadius = this.radius;
  35999. this._storedTarget = this._getTargetPosition().clone();
  36000. return _super.prototype.storeState.call(this);
  36001. };
  36002. /**
  36003. * Restored camera state. You must call storeState() first
  36004. */
  36005. ArcRotateCamera.prototype._restoreStateValues = function () {
  36006. if (!_super.prototype._restoreStateValues.call(this)) {
  36007. return false;
  36008. }
  36009. this.alpha = this._storedAlpha;
  36010. this.beta = this._storedBeta;
  36011. this.radius = this._storedRadius;
  36012. this.setTarget(this._storedTarget.clone());
  36013. this.inertialAlphaOffset = 0;
  36014. this.inertialBetaOffset = 0;
  36015. this.inertialRadiusOffset = 0;
  36016. this.inertialPanningX = 0;
  36017. this.inertialPanningY = 0;
  36018. return true;
  36019. };
  36020. // Synchronized
  36021. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  36022. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  36023. return false;
  36024. return this._cache._target.equals(this._getTargetPosition())
  36025. && this._cache.alpha === this.alpha
  36026. && this._cache.beta === this.beta
  36027. && this._cache.radius === this.radius
  36028. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  36029. };
  36030. // Methods
  36031. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  36032. var _this = this;
  36033. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  36034. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  36035. this._useCtrlForPanning = useCtrlForPanning;
  36036. this._panningMouseButton = panningMouseButton;
  36037. this.inputs.attachElement(element, noPreventDefault);
  36038. this._reset = function () {
  36039. _this.inertialAlphaOffset = 0;
  36040. _this.inertialBetaOffset = 0;
  36041. _this.inertialRadiusOffset = 0;
  36042. _this.inertialPanningX = 0;
  36043. _this.inertialPanningY = 0;
  36044. };
  36045. };
  36046. ArcRotateCamera.prototype.detachControl = function (element) {
  36047. this.inputs.detachElement(element);
  36048. if (this._reset) {
  36049. this._reset();
  36050. }
  36051. };
  36052. ArcRotateCamera.prototype._checkInputs = function () {
  36053. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  36054. if (this._collisionTriggered) {
  36055. return;
  36056. }
  36057. this.inputs.checkInputs();
  36058. // Inertia
  36059. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  36060. if (this.getScene().useRightHandedSystem) {
  36061. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  36062. }
  36063. else {
  36064. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  36065. }
  36066. this.beta += this.inertialBetaOffset;
  36067. this.radius -= this.inertialRadiusOffset;
  36068. this.inertialAlphaOffset *= this.inertia;
  36069. this.inertialBetaOffset *= this.inertia;
  36070. this.inertialRadiusOffset *= this.inertia;
  36071. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  36072. this.inertialAlphaOffset = 0;
  36073. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  36074. this.inertialBetaOffset = 0;
  36075. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  36076. this.inertialRadiusOffset = 0;
  36077. }
  36078. // Panning inertia
  36079. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  36080. if (!this._localDirection) {
  36081. this._localDirection = BABYLON.Vector3.Zero();
  36082. this._transformedDirection = BABYLON.Vector3.Zero();
  36083. }
  36084. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  36085. this._localDirection.multiplyInPlace(this.panningAxis);
  36086. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  36087. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  36088. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  36089. if (!this.panningAxis.y) {
  36090. this._transformedDirection.y = 0;
  36091. }
  36092. if (!this._targetHost) {
  36093. if (this.panningDistanceLimit) {
  36094. this._transformedDirection.addInPlace(this._target);
  36095. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  36096. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  36097. this._target.copyFrom(this._transformedDirection);
  36098. }
  36099. }
  36100. else {
  36101. this._target.addInPlace(this._transformedDirection);
  36102. }
  36103. }
  36104. this.inertialPanningX *= this.panningInertia;
  36105. this.inertialPanningY *= this.panningInertia;
  36106. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  36107. this.inertialPanningX = 0;
  36108. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  36109. this.inertialPanningY = 0;
  36110. }
  36111. // Limits
  36112. this._checkLimits();
  36113. _super.prototype._checkInputs.call(this);
  36114. };
  36115. ArcRotateCamera.prototype._checkLimits = function () {
  36116. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  36117. if (this.allowUpsideDown && this.beta > Math.PI) {
  36118. this.beta = this.beta - (2 * Math.PI);
  36119. }
  36120. }
  36121. else {
  36122. if (this.beta < this.lowerBetaLimit) {
  36123. this.beta = this.lowerBetaLimit;
  36124. }
  36125. }
  36126. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  36127. if (this.allowUpsideDown && this.beta < -Math.PI) {
  36128. this.beta = this.beta + (2 * Math.PI);
  36129. }
  36130. }
  36131. else {
  36132. if (this.beta > this.upperBetaLimit) {
  36133. this.beta = this.upperBetaLimit;
  36134. }
  36135. }
  36136. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  36137. this.alpha = this.lowerAlphaLimit;
  36138. }
  36139. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  36140. this.alpha = this.upperAlphaLimit;
  36141. }
  36142. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  36143. this.radius = this.lowerRadiusLimit;
  36144. }
  36145. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  36146. this.radius = this.upperRadiusLimit;
  36147. }
  36148. };
  36149. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  36150. var radiusv3 = this.position.subtract(this._getTargetPosition());
  36151. this.radius = radiusv3.length();
  36152. if (this.radius === 0) {
  36153. this.radius = 0.0001; // Just to avoid division by zero
  36154. }
  36155. // Alpha
  36156. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  36157. if (radiusv3.z < 0) {
  36158. this.alpha = 2 * Math.PI - this.alpha;
  36159. }
  36160. // Beta
  36161. this.beta = Math.acos(radiusv3.y / this.radius);
  36162. this._checkLimits();
  36163. };
  36164. ArcRotateCamera.prototype.setPosition = function (position) {
  36165. if (this.position.equals(position)) {
  36166. return;
  36167. }
  36168. this.position.copyFrom(position);
  36169. this.rebuildAnglesAndRadius();
  36170. };
  36171. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  36172. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  36173. if (allowSamePosition === void 0) { allowSamePosition = false; }
  36174. if (target.getBoundingInfo) {
  36175. if (toBoundingCenter) {
  36176. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  36177. }
  36178. else {
  36179. this._targetBoundingCenter = null;
  36180. }
  36181. this._targetHost = target;
  36182. this._target = this._getTargetPosition();
  36183. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  36184. }
  36185. else {
  36186. var newTarget = target;
  36187. var currentTarget = this._getTargetPosition();
  36188. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  36189. return;
  36190. }
  36191. this._targetHost = null;
  36192. this._target = newTarget;
  36193. this._targetBoundingCenter = null;
  36194. this.onMeshTargetChangedObservable.notifyObservers(null);
  36195. }
  36196. this.rebuildAnglesAndRadius();
  36197. };
  36198. ArcRotateCamera.prototype._getViewMatrix = function () {
  36199. // Compute
  36200. var cosa = Math.cos(this.alpha);
  36201. var sina = Math.sin(this.alpha);
  36202. var cosb = Math.cos(this.beta);
  36203. var sinb = Math.sin(this.beta);
  36204. if (sinb === 0) {
  36205. sinb = 0.0001;
  36206. }
  36207. var target = this._getTargetPosition();
  36208. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  36209. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  36210. if (!this._collider) {
  36211. this._collider = new BABYLON.Collider();
  36212. }
  36213. this._collider.radius = this.collisionRadius;
  36214. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  36215. this._collisionTriggered = true;
  36216. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  36217. }
  36218. else {
  36219. this.position.copyFrom(this._newPosition);
  36220. var up = this.upVector;
  36221. if (this.allowUpsideDown && sinb < 0) {
  36222. up = up.clone();
  36223. up = up.negate();
  36224. }
  36225. if (this.getScene().useRightHandedSystem) {
  36226. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  36227. }
  36228. else {
  36229. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  36230. }
  36231. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  36232. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  36233. }
  36234. this._currentTarget = target;
  36235. return this._viewMatrix;
  36236. };
  36237. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  36238. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  36239. meshes = meshes || this.getScene().meshes;
  36240. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  36241. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  36242. this.radius = distance * this.zoomOnFactor;
  36243. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  36244. };
  36245. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  36246. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  36247. var meshesOrMinMaxVector;
  36248. var distance;
  36249. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  36250. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  36251. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  36252. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  36253. }
  36254. else {
  36255. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  36256. distance = meshesOrMinMaxVectorAndDistance.distance;
  36257. }
  36258. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  36259. if (!doNotUpdateMaxZ) {
  36260. this.maxZ = distance * 2;
  36261. }
  36262. };
  36263. /**
  36264. * @override
  36265. * Override Camera.createRigCamera
  36266. */
  36267. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  36268. var alphaShift;
  36269. switch (this.cameraRigMode) {
  36270. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  36271. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  36272. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  36273. case BABYLON.Camera.RIG_MODE_VR:
  36274. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  36275. break;
  36276. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  36277. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  36278. break;
  36279. }
  36280. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  36281. rigCam._cameraRigParams = {};
  36282. return rigCam;
  36283. };
  36284. /**
  36285. * @override
  36286. * Override Camera._updateRigCameras
  36287. */
  36288. ArcRotateCamera.prototype._updateRigCameras = function () {
  36289. var camLeft = this._rigCameras[0];
  36290. var camRight = this._rigCameras[1];
  36291. camLeft.beta = camRight.beta = this.beta;
  36292. camLeft.radius = camRight.radius = this.radius;
  36293. switch (this.cameraRigMode) {
  36294. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  36295. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  36296. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  36297. case BABYLON.Camera.RIG_MODE_VR:
  36298. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  36299. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  36300. break;
  36301. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  36302. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  36303. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  36304. break;
  36305. }
  36306. _super.prototype._updateRigCameras.call(this);
  36307. };
  36308. ArcRotateCamera.prototype.dispose = function () {
  36309. this.inputs.clear();
  36310. _super.prototype.dispose.call(this);
  36311. };
  36312. ArcRotateCamera.prototype.getClassName = function () {
  36313. return "ArcRotateCamera";
  36314. };
  36315. return ArcRotateCamera;
  36316. }(BABYLON.TargetCamera));
  36317. __decorate([
  36318. BABYLON.serialize()
  36319. ], ArcRotateCamera.prototype, "alpha", void 0);
  36320. __decorate([
  36321. BABYLON.serialize()
  36322. ], ArcRotateCamera.prototype, "beta", void 0);
  36323. __decorate([
  36324. BABYLON.serialize()
  36325. ], ArcRotateCamera.prototype, "radius", void 0);
  36326. __decorate([
  36327. BABYLON.serializeAsVector3("target")
  36328. ], ArcRotateCamera.prototype, "_target", void 0);
  36329. __decorate([
  36330. BABYLON.serialize()
  36331. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  36332. __decorate([
  36333. BABYLON.serialize()
  36334. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  36335. __decorate([
  36336. BABYLON.serialize()
  36337. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  36338. __decorate([
  36339. BABYLON.serialize()
  36340. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  36341. __decorate([
  36342. BABYLON.serialize()
  36343. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  36344. __decorate([
  36345. BABYLON.serialize()
  36346. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  36347. __decorate([
  36348. BABYLON.serialize()
  36349. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  36350. __decorate([
  36351. BABYLON.serialize()
  36352. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  36353. __decorate([
  36354. BABYLON.serialize()
  36355. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  36356. __decorate([
  36357. BABYLON.serialize()
  36358. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  36359. __decorate([
  36360. BABYLON.serialize()
  36361. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  36362. __decorate([
  36363. BABYLON.serialize()
  36364. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  36365. __decorate([
  36366. BABYLON.serialize()
  36367. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  36368. __decorate([
  36369. BABYLON.serializeAsVector3()
  36370. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  36371. __decorate([
  36372. BABYLON.serialize()
  36373. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  36374. __decorate([
  36375. BABYLON.serialize()
  36376. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  36377. __decorate([
  36378. BABYLON.serialize()
  36379. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  36380. BABYLON.ArcRotateCamera = ArcRotateCamera;
  36381. })(BABYLON || (BABYLON = {}));
  36382. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  36383. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  36384. var BABYLON;
  36385. (function (BABYLON) {
  36386. var ArcRotateCameraInputsManager = (function (_super) {
  36387. __extends(ArcRotateCameraInputsManager, _super);
  36388. function ArcRotateCameraInputsManager(camera) {
  36389. return _super.call(this, camera) || this;
  36390. }
  36391. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  36392. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  36393. return this;
  36394. };
  36395. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  36396. this.add(new BABYLON.ArcRotateCameraPointersInput());
  36397. return this;
  36398. };
  36399. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  36400. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  36401. return this;
  36402. };
  36403. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  36404. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  36405. return this;
  36406. };
  36407. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  36408. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  36409. return this;
  36410. };
  36411. return ArcRotateCameraInputsManager;
  36412. }(BABYLON.CameraInputsManager));
  36413. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  36414. })(BABYLON || (BABYLON = {}));
  36415. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  36416. var BABYLON;
  36417. (function (BABYLON) {
  36418. var HemisphericLight = (function (_super) {
  36419. __extends(HemisphericLight, _super);
  36420. /**
  36421. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  36422. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  36423. * The HemisphericLight can't cast shadows.
  36424. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36425. */
  36426. function HemisphericLight(name, direction, scene) {
  36427. var _this = _super.call(this, name, scene) || this;
  36428. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  36429. _this.direction = direction || BABYLON.Vector3.Up();
  36430. return _this;
  36431. }
  36432. HemisphericLight.prototype._buildUniformLayout = function () {
  36433. this._uniformBuffer.addUniform("vLightData", 4);
  36434. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36435. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36436. this._uniformBuffer.addUniform("vLightGround", 3);
  36437. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36438. this._uniformBuffer.addUniform("depthValues", 2);
  36439. this._uniformBuffer.create();
  36440. };
  36441. /**
  36442. * Returns the string "HemisphericLight".
  36443. */
  36444. HemisphericLight.prototype.getClassName = function () {
  36445. return "HemisphericLight";
  36446. };
  36447. /**
  36448. * Sets the HemisphericLight direction towards the passed target (Vector3).
  36449. * Returns the updated direction.
  36450. */
  36451. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  36452. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  36453. return this.direction;
  36454. };
  36455. HemisphericLight.prototype.getShadowGenerator = function () {
  36456. return null;
  36457. };
  36458. /**
  36459. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  36460. * Returns the HemisphericLight.
  36461. */
  36462. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  36463. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36464. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  36465. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  36466. return this;
  36467. };
  36468. HemisphericLight.prototype._getWorldMatrix = function () {
  36469. if (!this._worldMatrix) {
  36470. this._worldMatrix = BABYLON.Matrix.Identity();
  36471. }
  36472. return this._worldMatrix;
  36473. };
  36474. /**
  36475. * Returns the integer 3.
  36476. */
  36477. HemisphericLight.prototype.getTypeID = function () {
  36478. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  36479. };
  36480. return HemisphericLight;
  36481. }(BABYLON.Light));
  36482. __decorate([
  36483. BABYLON.serializeAsColor3()
  36484. ], HemisphericLight.prototype, "groundColor", void 0);
  36485. __decorate([
  36486. BABYLON.serializeAsVector3()
  36487. ], HemisphericLight.prototype, "direction", void 0);
  36488. BABYLON.HemisphericLight = HemisphericLight;
  36489. })(BABYLON || (BABYLON = {}));
  36490. //# sourceMappingURL=babylon.hemisphericLight.js.map
  36491. var BABYLON;
  36492. (function (BABYLON) {
  36493. var ShadowLight = (function (_super) {
  36494. __extends(ShadowLight, _super);
  36495. function ShadowLight() {
  36496. var _this = _super !== null && _super.apply(this, arguments) || this;
  36497. _this._needProjectionMatrixCompute = true;
  36498. return _this;
  36499. }
  36500. Object.defineProperty(ShadowLight.prototype, "direction", {
  36501. get: function () {
  36502. return this._direction;
  36503. },
  36504. set: function (value) {
  36505. this._direction = value;
  36506. },
  36507. enumerable: true,
  36508. configurable: true
  36509. });
  36510. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  36511. get: function () {
  36512. return this._shadowMinZ;
  36513. },
  36514. set: function (value) {
  36515. this._shadowMinZ = value;
  36516. this.forceProjectionMatrixCompute();
  36517. },
  36518. enumerable: true,
  36519. configurable: true
  36520. });
  36521. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  36522. get: function () {
  36523. return this._shadowMaxZ;
  36524. },
  36525. set: function (value) {
  36526. this._shadowMaxZ = value;
  36527. this.forceProjectionMatrixCompute();
  36528. },
  36529. enumerable: true,
  36530. configurable: true
  36531. });
  36532. /**
  36533. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  36534. */
  36535. ShadowLight.prototype.computeTransformedInformation = function () {
  36536. if (this.parent && this.parent.getWorldMatrix) {
  36537. if (!this.transformedPosition) {
  36538. this.transformedPosition = BABYLON.Vector3.Zero();
  36539. }
  36540. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  36541. // In case the direction is present.
  36542. if (this.direction) {
  36543. if (!this.transformedDirection) {
  36544. this.transformedDirection = BABYLON.Vector3.Zero();
  36545. }
  36546. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  36547. }
  36548. return true;
  36549. }
  36550. return false;
  36551. };
  36552. /**
  36553. * Return the depth scale used for the shadow map.
  36554. */
  36555. ShadowLight.prototype.getDepthScale = function () {
  36556. return 50.0;
  36557. };
  36558. /**
  36559. * Returns the light direction (Vector3) for any passed face index.
  36560. */
  36561. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  36562. return this.transformedDirection ? this.transformedDirection : this.direction;
  36563. };
  36564. /**
  36565. * Returns the DirectionalLight absolute position in the World.
  36566. */
  36567. ShadowLight.prototype.getAbsolutePosition = function () {
  36568. return this.transformedPosition ? this.transformedPosition : this.position;
  36569. };
  36570. /**
  36571. * Sets the DirectionalLight direction toward the passed target (Vector3).
  36572. * Returns the updated DirectionalLight direction (Vector3).
  36573. */
  36574. ShadowLight.prototype.setDirectionToTarget = function (target) {
  36575. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  36576. return this.direction;
  36577. };
  36578. /**
  36579. * Returns the light rotation (Vector3).
  36580. */
  36581. ShadowLight.prototype.getRotation = function () {
  36582. this.direction.normalize();
  36583. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  36584. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  36585. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  36586. };
  36587. /**
  36588. * Boolean : false by default.
  36589. */
  36590. ShadowLight.prototype.needCube = function () {
  36591. return false;
  36592. };
  36593. /**
  36594. * Specifies wether or not the projection matrix should be recomputed this frame.
  36595. */
  36596. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  36597. return this._needProjectionMatrixCompute;
  36598. };
  36599. /**
  36600. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  36601. */
  36602. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  36603. this._needProjectionMatrixCompute = true;
  36604. };
  36605. /**
  36606. * Get the world matrix of the sahdow lights.
  36607. */
  36608. ShadowLight.prototype._getWorldMatrix = function () {
  36609. if (!this._worldMatrix) {
  36610. this._worldMatrix = BABYLON.Matrix.Identity();
  36611. }
  36612. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  36613. return this._worldMatrix;
  36614. };
  36615. /**
  36616. * Gets the minZ used for shadow according to both the scene and the light.
  36617. * @param activeCamera
  36618. */
  36619. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  36620. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  36621. };
  36622. /**
  36623. * Gets the maxZ used for shadow according to both the scene and the light.
  36624. * @param activeCamera
  36625. */
  36626. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  36627. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  36628. };
  36629. /**
  36630. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  36631. * Returns the light.
  36632. */
  36633. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36634. if (this.customProjectionMatrixBuilder) {
  36635. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  36636. }
  36637. else {
  36638. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36639. }
  36640. return this;
  36641. };
  36642. return ShadowLight;
  36643. }(BABYLON.Light));
  36644. __decorate([
  36645. BABYLON.serializeAsVector3()
  36646. ], ShadowLight.prototype, "position", void 0);
  36647. __decorate([
  36648. BABYLON.serializeAsVector3()
  36649. ], ShadowLight.prototype, "direction", null);
  36650. __decorate([
  36651. BABYLON.serialize()
  36652. ], ShadowLight.prototype, "shadowMinZ", null);
  36653. __decorate([
  36654. BABYLON.serialize()
  36655. ], ShadowLight.prototype, "shadowMaxZ", null);
  36656. BABYLON.ShadowLight = ShadowLight;
  36657. })(BABYLON || (BABYLON = {}));
  36658. //# sourceMappingURL=babylon.shadowLight.js.map
  36659. var BABYLON;
  36660. (function (BABYLON) {
  36661. var PointLight = (function (_super) {
  36662. __extends(PointLight, _super);
  36663. /**
  36664. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  36665. * A PointLight emits the light in every direction.
  36666. * It can cast shadows.
  36667. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  36668. * ```javascript
  36669. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  36670. * ```
  36671. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36672. */
  36673. function PointLight(name, position, scene) {
  36674. var _this = _super.call(this, name, scene) || this;
  36675. _this._shadowAngle = Math.PI / 2;
  36676. _this.position = position;
  36677. return _this;
  36678. }
  36679. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  36680. /**
  36681. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36682. * This specifies what angle the shadow will use to be created.
  36683. *
  36684. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36685. */
  36686. get: function () {
  36687. return this._shadowAngle;
  36688. },
  36689. /**
  36690. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36691. * This specifies what angle the shadow will use to be created.
  36692. *
  36693. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36694. */
  36695. set: function (value) {
  36696. this._shadowAngle = value;
  36697. this.forceProjectionMatrixCompute();
  36698. },
  36699. enumerable: true,
  36700. configurable: true
  36701. });
  36702. Object.defineProperty(PointLight.prototype, "direction", {
  36703. get: function () {
  36704. return this._direction;
  36705. },
  36706. /**
  36707. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36708. */
  36709. set: function (value) {
  36710. var previousNeedCube = this.needCube();
  36711. this._direction = value;
  36712. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  36713. this._shadowGenerator.recreateShadowMap();
  36714. }
  36715. },
  36716. enumerable: true,
  36717. configurable: true
  36718. });
  36719. /**
  36720. * Returns the string "PointLight"
  36721. */
  36722. PointLight.prototype.getClassName = function () {
  36723. return "PointLight";
  36724. };
  36725. /**
  36726. * Returns the integer 0.
  36727. */
  36728. PointLight.prototype.getTypeID = function () {
  36729. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  36730. };
  36731. /**
  36732. * Specifies wether or not the shadowmap should be a cube texture.
  36733. */
  36734. PointLight.prototype.needCube = function () {
  36735. return !this.direction;
  36736. };
  36737. /**
  36738. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  36739. */
  36740. PointLight.prototype.getShadowDirection = function (faceIndex) {
  36741. if (this.direction) {
  36742. return _super.prototype.getShadowDirection.call(this, faceIndex);
  36743. }
  36744. else {
  36745. switch (faceIndex) {
  36746. case 0:
  36747. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  36748. case 1:
  36749. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  36750. case 2:
  36751. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  36752. case 3:
  36753. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  36754. case 4:
  36755. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  36756. case 5:
  36757. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  36758. }
  36759. }
  36760. return BABYLON.Vector3.Zero();
  36761. };
  36762. /**
  36763. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  36764. * - fov = PI / 2
  36765. * - aspect ratio : 1.0
  36766. * - z-near and far equal to the active camera minZ and maxZ.
  36767. * Returns the PointLight.
  36768. */
  36769. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36770. var activeCamera = this.getScene().activeCamera;
  36771. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36772. };
  36773. PointLight.prototype._buildUniformLayout = function () {
  36774. this._uniformBuffer.addUniform("vLightData", 4);
  36775. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36776. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36777. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36778. this._uniformBuffer.addUniform("depthValues", 2);
  36779. this._uniformBuffer.create();
  36780. };
  36781. /**
  36782. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  36783. * Returns the PointLight.
  36784. */
  36785. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  36786. if (this.computeTransformedInformation()) {
  36787. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  36788. return this;
  36789. }
  36790. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36791. return this;
  36792. };
  36793. return PointLight;
  36794. }(BABYLON.ShadowLight));
  36795. __decorate([
  36796. BABYLON.serialize()
  36797. ], PointLight.prototype, "shadowAngle", null);
  36798. BABYLON.PointLight = PointLight;
  36799. })(BABYLON || (BABYLON = {}));
  36800. //# sourceMappingURL=babylon.pointLight.js.map
  36801. /// <reference path="babylon.light.ts" />
  36802. var BABYLON;
  36803. (function (BABYLON) {
  36804. var DirectionalLight = (function (_super) {
  36805. __extends(DirectionalLight, _super);
  36806. /**
  36807. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36808. * The directional light is emitted from everywhere in the given direction.
  36809. * It can cast shawdows.
  36810. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36811. */
  36812. function DirectionalLight(name, direction, scene) {
  36813. var _this = _super.call(this, name, scene) || this;
  36814. _this._shadowFrustumSize = 0;
  36815. _this._shadowOrthoScale = 0.5;
  36816. _this.autoUpdateExtends = true;
  36817. // Cache
  36818. _this._orthoLeft = Number.MAX_VALUE;
  36819. _this._orthoRight = Number.MIN_VALUE;
  36820. _this._orthoTop = Number.MIN_VALUE;
  36821. _this._orthoBottom = Number.MAX_VALUE;
  36822. _this.position = direction.scale(-1.0);
  36823. _this.direction = direction;
  36824. return _this;
  36825. }
  36826. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36827. /**
  36828. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36829. */
  36830. get: function () {
  36831. return this._shadowFrustumSize;
  36832. },
  36833. /**
  36834. * Specifies a fix frustum size for the shadow generation.
  36835. */
  36836. set: function (value) {
  36837. this._shadowFrustumSize = value;
  36838. this.forceProjectionMatrixCompute();
  36839. },
  36840. enumerable: true,
  36841. configurable: true
  36842. });
  36843. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36844. get: function () {
  36845. return this._shadowOrthoScale;
  36846. },
  36847. set: function (value) {
  36848. this._shadowOrthoScale = value;
  36849. this.forceProjectionMatrixCompute();
  36850. },
  36851. enumerable: true,
  36852. configurable: true
  36853. });
  36854. /**
  36855. * Returns the string "DirectionalLight".
  36856. */
  36857. DirectionalLight.prototype.getClassName = function () {
  36858. return "DirectionalLight";
  36859. };
  36860. /**
  36861. * Returns the integer 1.
  36862. */
  36863. DirectionalLight.prototype.getTypeID = function () {
  36864. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36865. };
  36866. /**
  36867. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36868. * Returns the DirectionalLight Shadow projection matrix.
  36869. */
  36870. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36871. if (this.shadowFrustumSize > 0) {
  36872. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36873. }
  36874. else {
  36875. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36876. }
  36877. };
  36878. /**
  36879. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36880. * Returns the DirectionalLight Shadow projection matrix.
  36881. */
  36882. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36883. var activeCamera = this.getScene().activeCamera;
  36884. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36885. };
  36886. /**
  36887. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36888. * Returns the DirectionalLight Shadow projection matrix.
  36889. */
  36890. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36891. var activeCamera = this.getScene().activeCamera;
  36892. // Check extends
  36893. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36894. var tempVector3 = BABYLON.Vector3.Zero();
  36895. this._orthoLeft = Number.MAX_VALUE;
  36896. this._orthoRight = Number.MIN_VALUE;
  36897. this._orthoTop = Number.MIN_VALUE;
  36898. this._orthoBottom = Number.MAX_VALUE;
  36899. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36900. var mesh = renderList[meshIndex];
  36901. if (!mesh) {
  36902. continue;
  36903. }
  36904. var boundingInfo = mesh.getBoundingInfo();
  36905. if (!boundingInfo) {
  36906. continue;
  36907. }
  36908. var boundingBox = boundingInfo.boundingBox;
  36909. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36910. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36911. if (tempVector3.x < this._orthoLeft)
  36912. this._orthoLeft = tempVector3.x;
  36913. if (tempVector3.y < this._orthoBottom)
  36914. this._orthoBottom = tempVector3.y;
  36915. if (tempVector3.x > this._orthoRight)
  36916. this._orthoRight = tempVector3.x;
  36917. if (tempVector3.y > this._orthoTop)
  36918. this._orthoTop = tempVector3.y;
  36919. }
  36920. }
  36921. }
  36922. var xOffset = this._orthoRight - this._orthoLeft;
  36923. var yOffset = this._orthoTop - this._orthoBottom;
  36924. 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);
  36925. };
  36926. DirectionalLight.prototype._buildUniformLayout = function () {
  36927. this._uniformBuffer.addUniform("vLightData", 4);
  36928. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36929. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36930. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36931. this._uniformBuffer.addUniform("depthValues", 2);
  36932. this._uniformBuffer.create();
  36933. };
  36934. /**
  36935. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36936. * Returns the DirectionalLight.
  36937. */
  36938. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36939. if (this.computeTransformedInformation()) {
  36940. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36941. return this;
  36942. }
  36943. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36944. return this;
  36945. };
  36946. /**
  36947. * Gets the minZ used for shadow according to both the scene and the light.
  36948. *
  36949. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36950. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36951. * @param activeCamera
  36952. */
  36953. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36954. return 1;
  36955. };
  36956. /**
  36957. * Gets the maxZ used for shadow according to both the scene and the light.
  36958. *
  36959. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36960. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36961. * @param activeCamera
  36962. */
  36963. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36964. return 1;
  36965. };
  36966. return DirectionalLight;
  36967. }(BABYLON.ShadowLight));
  36968. __decorate([
  36969. BABYLON.serialize()
  36970. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36971. __decorate([
  36972. BABYLON.serialize()
  36973. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36974. __decorate([
  36975. BABYLON.serialize()
  36976. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36977. BABYLON.DirectionalLight = DirectionalLight;
  36978. })(BABYLON || (BABYLON = {}));
  36979. //# sourceMappingURL=babylon.directionalLight.js.map
  36980. var BABYLON;
  36981. (function (BABYLON) {
  36982. var SpotLight = (function (_super) {
  36983. __extends(SpotLight, _super);
  36984. /**
  36985. * Creates a SpotLight object in the scene with the passed parameters :
  36986. * - `position` (Vector3) is the initial SpotLight position,
  36987. * - `direction` (Vector3) is the initial SpotLight direction,
  36988. * - `angle` (float, in radians) is the spot light cone angle,
  36989. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36990. * A spot light is a simply light oriented cone.
  36991. * It can cast shadows.
  36992. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36993. */
  36994. function SpotLight(name, position, direction, angle, exponent, scene) {
  36995. var _this = _super.call(this, name, scene) || this;
  36996. _this.position = position;
  36997. _this.direction = direction;
  36998. _this.angle = angle;
  36999. _this.exponent = exponent;
  37000. return _this;
  37001. }
  37002. Object.defineProperty(SpotLight.prototype, "angle", {
  37003. get: function () {
  37004. return this._angle;
  37005. },
  37006. set: function (value) {
  37007. this._angle = value;
  37008. this.forceProjectionMatrixCompute();
  37009. },
  37010. enumerable: true,
  37011. configurable: true
  37012. });
  37013. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  37014. get: function () {
  37015. return this._shadowAngleScale;
  37016. },
  37017. /**
  37018. * Allows scaling the angle of the light for shadow generation only.
  37019. */
  37020. set: function (value) {
  37021. this._shadowAngleScale = value;
  37022. this.forceProjectionMatrixCompute();
  37023. },
  37024. enumerable: true,
  37025. configurable: true
  37026. });
  37027. /**
  37028. * Returns the string "SpotLight".
  37029. */
  37030. SpotLight.prototype.getClassName = function () {
  37031. return "SpotLight";
  37032. };
  37033. /**
  37034. * Returns the integer 2.
  37035. */
  37036. SpotLight.prototype.getTypeID = function () {
  37037. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  37038. };
  37039. /**
  37040. * 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.
  37041. * Returns the SpotLight.
  37042. */
  37043. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  37044. var activeCamera = this.getScene().activeCamera;
  37045. this._shadowAngleScale = this._shadowAngleScale || 1;
  37046. var angle = this._shadowAngleScale * this._angle;
  37047. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  37048. };
  37049. SpotLight.prototype._buildUniformLayout = function () {
  37050. this._uniformBuffer.addUniform("vLightData", 4);
  37051. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  37052. this._uniformBuffer.addUniform("vLightSpecular", 3);
  37053. this._uniformBuffer.addUniform("vLightDirection", 3);
  37054. this._uniformBuffer.addUniform("shadowsInfo", 3);
  37055. this._uniformBuffer.addUniform("depthValues", 2);
  37056. this._uniformBuffer.create();
  37057. };
  37058. /**
  37059. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  37060. * Return the SpotLight.
  37061. */
  37062. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  37063. var normalizeDirection;
  37064. if (this.computeTransformedInformation()) {
  37065. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  37066. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  37067. }
  37068. else {
  37069. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  37070. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  37071. }
  37072. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  37073. return this;
  37074. };
  37075. return SpotLight;
  37076. }(BABYLON.ShadowLight));
  37077. __decorate([
  37078. BABYLON.serialize()
  37079. ], SpotLight.prototype, "angle", null);
  37080. __decorate([
  37081. BABYLON.serialize()
  37082. /**
  37083. * Allows scaling the angle of the light for shadow generation only.
  37084. */
  37085. ], SpotLight.prototype, "shadowAngleScale", null);
  37086. __decorate([
  37087. BABYLON.serialize()
  37088. ], SpotLight.prototype, "exponent", void 0);
  37089. BABYLON.SpotLight = SpotLight;
  37090. })(BABYLON || (BABYLON = {}));
  37091. //# sourceMappingURL=babylon.spotLight.js.map
  37092. var BABYLON;
  37093. (function (BABYLON) {
  37094. var AnimationRange = (function () {
  37095. function AnimationRange(name, from, to) {
  37096. this.name = name;
  37097. this.from = from;
  37098. this.to = to;
  37099. }
  37100. AnimationRange.prototype.clone = function () {
  37101. return new AnimationRange(this.name, this.from, this.to);
  37102. };
  37103. return AnimationRange;
  37104. }());
  37105. BABYLON.AnimationRange = AnimationRange;
  37106. /**
  37107. * Composed of a frame, and an action function
  37108. */
  37109. var AnimationEvent = (function () {
  37110. function AnimationEvent(frame, action, onlyOnce) {
  37111. this.frame = frame;
  37112. this.action = action;
  37113. this.onlyOnce = onlyOnce;
  37114. this.isDone = false;
  37115. }
  37116. return AnimationEvent;
  37117. }());
  37118. BABYLON.AnimationEvent = AnimationEvent;
  37119. var PathCursor = (function () {
  37120. function PathCursor(path) {
  37121. this.path = path;
  37122. this._onchange = new Array();
  37123. this.value = 0;
  37124. this.animations = new Array();
  37125. }
  37126. PathCursor.prototype.getPoint = function () {
  37127. var point = this.path.getPointAtLengthPosition(this.value);
  37128. return new BABYLON.Vector3(point.x, 0, point.y);
  37129. };
  37130. PathCursor.prototype.moveAhead = function (step) {
  37131. if (step === void 0) { step = 0.002; }
  37132. this.move(step);
  37133. return this;
  37134. };
  37135. PathCursor.prototype.moveBack = function (step) {
  37136. if (step === void 0) { step = 0.002; }
  37137. this.move(-step);
  37138. return this;
  37139. };
  37140. PathCursor.prototype.move = function (step) {
  37141. if (Math.abs(step) > 1) {
  37142. throw "step size should be less than 1.";
  37143. }
  37144. this.value += step;
  37145. this.ensureLimits();
  37146. this.raiseOnChange();
  37147. return this;
  37148. };
  37149. PathCursor.prototype.ensureLimits = function () {
  37150. while (this.value > 1) {
  37151. this.value -= 1;
  37152. }
  37153. while (this.value < 0) {
  37154. this.value += 1;
  37155. }
  37156. return this;
  37157. };
  37158. // used by animation engine
  37159. PathCursor.prototype.markAsDirty = function (propertyName) {
  37160. this.ensureLimits();
  37161. this.raiseOnChange();
  37162. return this;
  37163. };
  37164. PathCursor.prototype.raiseOnChange = function () {
  37165. var _this = this;
  37166. this._onchange.forEach(function (f) { return f(_this); });
  37167. return this;
  37168. };
  37169. PathCursor.prototype.onchange = function (f) {
  37170. this._onchange.push(f);
  37171. return this;
  37172. };
  37173. return PathCursor;
  37174. }());
  37175. BABYLON.PathCursor = PathCursor;
  37176. var Animation = (function () {
  37177. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  37178. this.name = name;
  37179. this.targetProperty = targetProperty;
  37180. this.framePerSecond = framePerSecond;
  37181. this.dataType = dataType;
  37182. this.loopMode = loopMode;
  37183. this.enableBlending = enableBlending;
  37184. this._runtimeAnimations = new Array();
  37185. // The set of event that will be linked to this animation
  37186. this._events = new Array();
  37187. this.blendingSpeed = 0.01;
  37188. this._ranges = {};
  37189. this.targetPropertyPath = targetProperty.split(".");
  37190. this.dataType = dataType;
  37191. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  37192. }
  37193. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  37194. var dataType = undefined;
  37195. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  37196. dataType = Animation.ANIMATIONTYPE_FLOAT;
  37197. }
  37198. else if (from instanceof BABYLON.Quaternion) {
  37199. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  37200. }
  37201. else if (from instanceof BABYLON.Vector3) {
  37202. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  37203. }
  37204. else if (from instanceof BABYLON.Vector2) {
  37205. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  37206. }
  37207. else if (from instanceof BABYLON.Color3) {
  37208. dataType = Animation.ANIMATIONTYPE_COLOR3;
  37209. }
  37210. else if (from instanceof BABYLON.Size) {
  37211. dataType = Animation.ANIMATIONTYPE_SIZE;
  37212. }
  37213. if (dataType == undefined) {
  37214. return null;
  37215. }
  37216. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  37217. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  37218. animation.setKeys(keys);
  37219. if (easingFunction !== undefined) {
  37220. animation.setEasingFunction(easingFunction);
  37221. }
  37222. return animation;
  37223. };
  37224. /**
  37225. * Sets up an animation.
  37226. * @param property the property to animate
  37227. * @param animationType the animation type to apply
  37228. * @param easingFunction the easing function used in the animation
  37229. * @returns The created animation
  37230. */
  37231. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  37232. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  37233. animation.setEasingFunction(easingFunction);
  37234. return animation;
  37235. };
  37236. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  37237. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  37238. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  37239. };
  37240. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  37241. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  37242. node.animations.push(animation);
  37243. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  37244. };
  37245. /**
  37246. * Transition property of the Camera to the target Value.
  37247. * @param property The property to transition
  37248. * @param targetValue The target Value of the property
  37249. * @param host The object where the property to animate belongs
  37250. * @param scene Scene used to run the animation
  37251. * @param frameRate Framerate (in frame/s) to use
  37252. * @param transition The transition type we want to use
  37253. * @param duration The duration of the animation, in milliseconds
  37254. * @param onAnimationEnd Call back trigger at the end of the animation.
  37255. */
  37256. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  37257. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  37258. if (duration <= 0) {
  37259. host[property] = targetValue;
  37260. if (onAnimationEnd) {
  37261. onAnimationEnd();
  37262. }
  37263. return;
  37264. }
  37265. var endFrame = frameRate * (duration / 1000);
  37266. transition.setKeys([{
  37267. frame: 0,
  37268. value: host[property].clone ? host[property].clone() : host[property]
  37269. },
  37270. {
  37271. frame: endFrame,
  37272. value: targetValue
  37273. }]);
  37274. if (!host.animations) {
  37275. host.animations = [];
  37276. }
  37277. host.animations.push(transition);
  37278. var animation = scene.beginAnimation(host, 0, endFrame, false);
  37279. animation.onAnimationEnd = onAnimationEnd;
  37280. return animation;
  37281. };
  37282. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  37283. /**
  37284. * Return the array of runtime animations currently using this animation
  37285. */
  37286. get: function () {
  37287. return this._runtimeAnimations;
  37288. },
  37289. enumerable: true,
  37290. configurable: true
  37291. });
  37292. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  37293. get: function () {
  37294. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  37295. var runtimeAnimation = _a[_i];
  37296. if (!runtimeAnimation.isStopped) {
  37297. return true;
  37298. }
  37299. }
  37300. return false;
  37301. },
  37302. enumerable: true,
  37303. configurable: true
  37304. });
  37305. // Methods
  37306. /**
  37307. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  37308. */
  37309. Animation.prototype.toString = function (fullDetails) {
  37310. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  37311. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  37312. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  37313. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  37314. if (fullDetails) {
  37315. ret += ", Ranges: {";
  37316. var first = true;
  37317. for (var name in this._ranges) {
  37318. if (first) {
  37319. ret += ", ";
  37320. first = false;
  37321. }
  37322. ret += name;
  37323. }
  37324. ret += "}";
  37325. }
  37326. return ret;
  37327. };
  37328. /**
  37329. * Add an event to this animation.
  37330. */
  37331. Animation.prototype.addEvent = function (event) {
  37332. this._events.push(event);
  37333. };
  37334. /**
  37335. * Remove all events found at the given frame
  37336. * @param frame
  37337. */
  37338. Animation.prototype.removeEvents = function (frame) {
  37339. for (var index = 0; index < this._events.length; index++) {
  37340. if (this._events[index].frame === frame) {
  37341. this._events.splice(index, 1);
  37342. index--;
  37343. }
  37344. }
  37345. };
  37346. Animation.prototype.getEvents = function () {
  37347. return this._events;
  37348. };
  37349. Animation.prototype.createRange = function (name, from, to) {
  37350. // check name not already in use; could happen for bones after serialized
  37351. if (!this._ranges[name]) {
  37352. this._ranges[name] = new AnimationRange(name, from, to);
  37353. }
  37354. };
  37355. Animation.prototype.deleteRange = function (name, deleteFrames) {
  37356. if (deleteFrames === void 0) { deleteFrames = true; }
  37357. if (this._ranges[name]) {
  37358. if (deleteFrames) {
  37359. var from = this._ranges[name].from;
  37360. var to = this._ranges[name].to;
  37361. // this loop MUST go high to low for multiple splices to work
  37362. for (var key = this._keys.length - 1; key >= 0; key--) {
  37363. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  37364. this._keys.splice(key, 1);
  37365. }
  37366. }
  37367. }
  37368. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  37369. }
  37370. };
  37371. Animation.prototype.getRange = function (name) {
  37372. return this._ranges[name];
  37373. };
  37374. Animation.prototype.getKeys = function () {
  37375. return this._keys;
  37376. };
  37377. Animation.prototype.getHighestFrame = function () {
  37378. var ret = 0;
  37379. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  37380. if (ret < this._keys[key].frame) {
  37381. ret = this._keys[key].frame;
  37382. }
  37383. }
  37384. return ret;
  37385. };
  37386. Animation.prototype.getEasingFunction = function () {
  37387. return this._easingFunction;
  37388. };
  37389. Animation.prototype.setEasingFunction = function (easingFunction) {
  37390. this._easingFunction = easingFunction;
  37391. };
  37392. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  37393. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  37394. };
  37395. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37396. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37397. };
  37398. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  37399. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  37400. };
  37401. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37402. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  37403. };
  37404. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  37405. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  37406. };
  37407. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37408. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37409. };
  37410. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  37411. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  37412. };
  37413. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37414. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37415. };
  37416. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  37417. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  37418. };
  37419. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  37420. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  37421. };
  37422. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  37423. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  37424. };
  37425. Animation.prototype.clone = function () {
  37426. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  37427. clone.enableBlending = this.enableBlending;
  37428. clone.blendingSpeed = this.blendingSpeed;
  37429. if (this._keys) {
  37430. clone.setKeys(this._keys);
  37431. }
  37432. if (this._ranges) {
  37433. clone._ranges = {};
  37434. for (var name in this._ranges) {
  37435. clone._ranges[name] = this._ranges[name].clone();
  37436. }
  37437. }
  37438. return clone;
  37439. };
  37440. Animation.prototype.setKeys = function (values) {
  37441. this._keys = values.slice(0);
  37442. };
  37443. Animation.prototype.serialize = function () {
  37444. var serializationObject = {};
  37445. serializationObject.name = this.name;
  37446. serializationObject.property = this.targetProperty;
  37447. serializationObject.framePerSecond = this.framePerSecond;
  37448. serializationObject.dataType = this.dataType;
  37449. serializationObject.loopBehavior = this.loopMode;
  37450. serializationObject.enableBlending = this.enableBlending;
  37451. serializationObject.blendingSpeed = this.blendingSpeed;
  37452. var dataType = this.dataType;
  37453. serializationObject.keys = [];
  37454. var keys = this.getKeys();
  37455. for (var index = 0; index < keys.length; index++) {
  37456. var animationKey = keys[index];
  37457. var key = {};
  37458. key.frame = animationKey.frame;
  37459. switch (dataType) {
  37460. case Animation.ANIMATIONTYPE_FLOAT:
  37461. key.values = [animationKey.value];
  37462. break;
  37463. case Animation.ANIMATIONTYPE_QUATERNION:
  37464. case Animation.ANIMATIONTYPE_MATRIX:
  37465. case Animation.ANIMATIONTYPE_VECTOR3:
  37466. case Animation.ANIMATIONTYPE_COLOR3:
  37467. key.values = animationKey.value.asArray();
  37468. break;
  37469. }
  37470. serializationObject.keys.push(key);
  37471. }
  37472. serializationObject.ranges = [];
  37473. for (var name in this._ranges) {
  37474. var range = {};
  37475. range.name = name;
  37476. range.from = this._ranges[name].from;
  37477. range.to = this._ranges[name].to;
  37478. serializationObject.ranges.push(range);
  37479. }
  37480. return serializationObject;
  37481. };
  37482. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  37483. get: function () {
  37484. return Animation._ANIMATIONTYPE_FLOAT;
  37485. },
  37486. enumerable: true,
  37487. configurable: true
  37488. });
  37489. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  37490. get: function () {
  37491. return Animation._ANIMATIONTYPE_VECTOR3;
  37492. },
  37493. enumerable: true,
  37494. configurable: true
  37495. });
  37496. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  37497. get: function () {
  37498. return Animation._ANIMATIONTYPE_VECTOR2;
  37499. },
  37500. enumerable: true,
  37501. configurable: true
  37502. });
  37503. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  37504. get: function () {
  37505. return Animation._ANIMATIONTYPE_SIZE;
  37506. },
  37507. enumerable: true,
  37508. configurable: true
  37509. });
  37510. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  37511. get: function () {
  37512. return Animation._ANIMATIONTYPE_QUATERNION;
  37513. },
  37514. enumerable: true,
  37515. configurable: true
  37516. });
  37517. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  37518. get: function () {
  37519. return Animation._ANIMATIONTYPE_MATRIX;
  37520. },
  37521. enumerable: true,
  37522. configurable: true
  37523. });
  37524. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  37525. get: function () {
  37526. return Animation._ANIMATIONTYPE_COLOR3;
  37527. },
  37528. enumerable: true,
  37529. configurable: true
  37530. });
  37531. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  37532. get: function () {
  37533. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  37534. },
  37535. enumerable: true,
  37536. configurable: true
  37537. });
  37538. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  37539. get: function () {
  37540. return Animation._ANIMATIONLOOPMODE_CYCLE;
  37541. },
  37542. enumerable: true,
  37543. configurable: true
  37544. });
  37545. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  37546. get: function () {
  37547. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  37548. },
  37549. enumerable: true,
  37550. configurable: true
  37551. });
  37552. Animation.Parse = function (parsedAnimation) {
  37553. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  37554. var dataType = parsedAnimation.dataType;
  37555. var keys = [];
  37556. var data;
  37557. var index;
  37558. if (parsedAnimation.enableBlending) {
  37559. animation.enableBlending = parsedAnimation.enableBlending;
  37560. }
  37561. if (parsedAnimation.blendingSpeed) {
  37562. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  37563. }
  37564. for (index = 0; index < parsedAnimation.keys.length; index++) {
  37565. var key = parsedAnimation.keys[index];
  37566. switch (dataType) {
  37567. case Animation.ANIMATIONTYPE_FLOAT:
  37568. data = key.values[0];
  37569. break;
  37570. case Animation.ANIMATIONTYPE_QUATERNION:
  37571. data = BABYLON.Quaternion.FromArray(key.values);
  37572. break;
  37573. case Animation.ANIMATIONTYPE_MATRIX:
  37574. data = BABYLON.Matrix.FromArray(key.values);
  37575. break;
  37576. case Animation.ANIMATIONTYPE_COLOR3:
  37577. data = BABYLON.Color3.FromArray(key.values);
  37578. break;
  37579. case Animation.ANIMATIONTYPE_VECTOR3:
  37580. default:
  37581. data = BABYLON.Vector3.FromArray(key.values);
  37582. break;
  37583. }
  37584. keys.push({
  37585. frame: key.frame,
  37586. value: data
  37587. });
  37588. }
  37589. animation.setKeys(keys);
  37590. if (parsedAnimation.ranges) {
  37591. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  37592. data = parsedAnimation.ranges[index];
  37593. animation.createRange(data.name, data.from, data.to);
  37594. }
  37595. }
  37596. return animation;
  37597. };
  37598. Animation.AppendSerializedAnimations = function (source, destination) {
  37599. if (source.animations) {
  37600. destination.animations = [];
  37601. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  37602. var animation = source.animations[animationIndex];
  37603. destination.animations.push(animation.serialize());
  37604. }
  37605. }
  37606. };
  37607. return Animation;
  37608. }());
  37609. Animation.AllowMatricesInterpolation = false;
  37610. // Statics
  37611. Animation._ANIMATIONTYPE_FLOAT = 0;
  37612. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  37613. Animation._ANIMATIONTYPE_QUATERNION = 2;
  37614. Animation._ANIMATIONTYPE_MATRIX = 3;
  37615. Animation._ANIMATIONTYPE_COLOR3 = 4;
  37616. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  37617. Animation._ANIMATIONTYPE_SIZE = 6;
  37618. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  37619. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  37620. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  37621. BABYLON.Animation = Animation;
  37622. })(BABYLON || (BABYLON = {}));
  37623. //# sourceMappingURL=babylon.animation.js.map
  37624. var BABYLON;
  37625. (function (BABYLON) {
  37626. var RuntimeAnimation = (function () {
  37627. function RuntimeAnimation(target, animation) {
  37628. this._offsetsCache = {};
  37629. this._highLimitsCache = {};
  37630. this._stopped = false;
  37631. this._blendingFactor = 0;
  37632. this._ratioOffset = 0;
  37633. this._animation = animation;
  37634. this._target = target;
  37635. animation._runtimeAnimations.push(this);
  37636. }
  37637. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  37638. get: function () {
  37639. return this._animation;
  37640. },
  37641. enumerable: true,
  37642. configurable: true
  37643. });
  37644. RuntimeAnimation.prototype.reset = function () {
  37645. this._offsetsCache = {};
  37646. this._highLimitsCache = {};
  37647. this.currentFrame = 0;
  37648. this._blendingFactor = 0;
  37649. this._originalBlendValue = null;
  37650. };
  37651. RuntimeAnimation.prototype.isStopped = function () {
  37652. return this._stopped;
  37653. };
  37654. RuntimeAnimation.prototype.dispose = function () {
  37655. var index = this._animation.runtimeAnimations.indexOf(this);
  37656. if (index > -1) {
  37657. this._animation.runtimeAnimations.splice(index, 1);
  37658. }
  37659. };
  37660. RuntimeAnimation.prototype._getKeyValue = function (value) {
  37661. if (typeof value === "function") {
  37662. return value();
  37663. }
  37664. return value;
  37665. };
  37666. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  37667. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  37668. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  37669. }
  37670. this.currentFrame = currentFrame;
  37671. var keys = this._animation.getKeys();
  37672. // Try to get a hash to find the right key
  37673. 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));
  37674. if (keys[startKeyIndex].frame >= currentFrame) {
  37675. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  37676. startKeyIndex--;
  37677. }
  37678. }
  37679. for (var key = startKeyIndex; key < keys.length; key++) {
  37680. var endKey = keys[key + 1];
  37681. if (endKey.frame >= currentFrame) {
  37682. var startKey = keys[key];
  37683. var startValue = this._getKeyValue(startKey.value);
  37684. var endValue = this._getKeyValue(endKey.value);
  37685. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  37686. var frameDelta = endKey.frame - startKey.frame;
  37687. // gradient : percent of currentFrame between the frame inf and the frame sup
  37688. var gradient = (currentFrame - startKey.frame) / frameDelta;
  37689. // check for easingFunction and correction of gradient
  37690. var easingFunction = this._animation.getEasingFunction();
  37691. if (easingFunction != null) {
  37692. gradient = easingFunction.ease(gradient);
  37693. }
  37694. switch (this._animation.dataType) {
  37695. // Float
  37696. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  37697. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  37698. switch (loopMode) {
  37699. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37700. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37701. return floatValue;
  37702. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37703. return offsetValue * repeatCount + floatValue;
  37704. }
  37705. break;
  37706. // Quaternion
  37707. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  37708. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  37709. switch (loopMode) {
  37710. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37711. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37712. return quatValue;
  37713. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37714. return quatValue.add(offsetValue.scale(repeatCount));
  37715. }
  37716. return quatValue;
  37717. // Vector3
  37718. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  37719. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  37720. switch (loopMode) {
  37721. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37722. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37723. return vec3Value;
  37724. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37725. return vec3Value.add(offsetValue.scale(repeatCount));
  37726. }
  37727. // Vector2
  37728. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  37729. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  37730. switch (loopMode) {
  37731. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37732. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37733. return vec2Value;
  37734. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37735. return vec2Value.add(offsetValue.scale(repeatCount));
  37736. }
  37737. // Size
  37738. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  37739. switch (loopMode) {
  37740. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37741. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37742. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  37743. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37744. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  37745. }
  37746. // Color3
  37747. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  37748. switch (loopMode) {
  37749. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37750. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37751. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  37752. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37753. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  37754. }
  37755. // Matrix
  37756. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  37757. switch (loopMode) {
  37758. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37759. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37760. if (BABYLON.Animation.AllowMatricesInterpolation) {
  37761. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  37762. }
  37763. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37764. return startValue;
  37765. }
  37766. default:
  37767. break;
  37768. }
  37769. break;
  37770. }
  37771. }
  37772. return this._getKeyValue(keys[keys.length - 1].value);
  37773. };
  37774. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  37775. if (blend === void 0) { blend = false; }
  37776. // Set value
  37777. var path;
  37778. var destination;
  37779. var targetPropertyPath = this._animation.targetPropertyPath;
  37780. if (targetPropertyPath.length > 1) {
  37781. var property = this._target[targetPropertyPath[0]];
  37782. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  37783. property = property[targetPropertyPath[index]];
  37784. }
  37785. path = targetPropertyPath[targetPropertyPath.length - 1];
  37786. destination = property;
  37787. }
  37788. else {
  37789. path = targetPropertyPath[0];
  37790. destination = this._target;
  37791. }
  37792. // Blending
  37793. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  37794. if (!this._originalBlendValue) {
  37795. if (destination[path].clone) {
  37796. this._originalBlendValue = destination[path].clone();
  37797. }
  37798. else {
  37799. this._originalBlendValue = destination[path];
  37800. }
  37801. }
  37802. if (this._originalBlendValue.prototype) {
  37803. if (this._originalBlendValue.prototype.Lerp) {
  37804. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  37805. }
  37806. else {
  37807. destination[path] = currentValue;
  37808. }
  37809. }
  37810. else if (this._originalBlendValue.m) {
  37811. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  37812. }
  37813. else {
  37814. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  37815. }
  37816. this._blendingFactor += this._animation.blendingSpeed;
  37817. }
  37818. else {
  37819. destination[path] = currentValue;
  37820. }
  37821. if (this._target.markAsDirty) {
  37822. this._target.markAsDirty(this._animation.targetProperty);
  37823. }
  37824. };
  37825. RuntimeAnimation.prototype.goToFrame = function (frame) {
  37826. var keys = this._animation.getKeys();
  37827. if (frame < keys[0].frame) {
  37828. frame = keys[0].frame;
  37829. }
  37830. else if (frame > keys[keys.length - 1].frame) {
  37831. frame = keys[keys.length - 1].frame;
  37832. }
  37833. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  37834. this.setValue(currentValue);
  37835. };
  37836. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  37837. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  37838. this._ratioOffset = this._previousRatio - newRatio;
  37839. };
  37840. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  37841. if (blend === void 0) { blend = false; }
  37842. var targetPropertyPath = this._animation.targetPropertyPath;
  37843. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  37844. this._stopped = true;
  37845. return false;
  37846. }
  37847. var returnValue = true;
  37848. var keys = this._animation.getKeys();
  37849. // Adding a start key at frame 0 if missing
  37850. if (keys[0].frame !== 0) {
  37851. var newKey = { frame: 0, value: keys[0].value };
  37852. keys.splice(0, 0, newKey);
  37853. }
  37854. // Check limits
  37855. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  37856. from = keys[0].frame;
  37857. }
  37858. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  37859. to = keys[keys.length - 1].frame;
  37860. }
  37861. //to and from cannot be the same key
  37862. if (from === to) {
  37863. if (from > keys[0].frame) {
  37864. from--;
  37865. }
  37866. else if (to < keys[keys.length - 1].frame) {
  37867. to++;
  37868. }
  37869. }
  37870. // Compute ratio
  37871. var range = to - from;
  37872. var offsetValue;
  37873. // ratio represents the frame delta between from and to
  37874. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  37875. var highLimitValue = 0;
  37876. this._previousDelay = delay;
  37877. this._previousRatio = ratio;
  37878. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  37879. returnValue = false;
  37880. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  37881. }
  37882. else {
  37883. // Get max value if required
  37884. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  37885. var keyOffset = to.toString() + from.toString();
  37886. if (!this._offsetsCache[keyOffset]) {
  37887. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  37888. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  37889. switch (this._animation.dataType) {
  37890. // Float
  37891. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  37892. this._offsetsCache[keyOffset] = toValue - fromValue;
  37893. break;
  37894. // Quaternion
  37895. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  37896. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37897. break;
  37898. // Vector3
  37899. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  37900. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37901. // Vector2
  37902. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  37903. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37904. // Size
  37905. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  37906. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37907. // Color3
  37908. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  37909. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37910. default:
  37911. break;
  37912. }
  37913. this._highLimitsCache[keyOffset] = toValue;
  37914. }
  37915. highLimitValue = this._highLimitsCache[keyOffset];
  37916. offsetValue = this._offsetsCache[keyOffset];
  37917. }
  37918. }
  37919. if (offsetValue === undefined) {
  37920. switch (this._animation.dataType) {
  37921. // Float
  37922. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  37923. offsetValue = 0;
  37924. break;
  37925. // Quaternion
  37926. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  37927. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  37928. break;
  37929. // Vector3
  37930. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  37931. offsetValue = BABYLON.Vector3.Zero();
  37932. break;
  37933. // Vector2
  37934. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  37935. offsetValue = BABYLON.Vector2.Zero();
  37936. break;
  37937. // Size
  37938. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  37939. offsetValue = BABYLON.Size.Zero();
  37940. break;
  37941. // Color3
  37942. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  37943. offsetValue = BABYLON.Color3.Black();
  37944. }
  37945. }
  37946. // Compute value
  37947. var repeatCount = (ratio / range) >> 0;
  37948. var currentFrame = returnValue ? from + ratio % range : to;
  37949. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  37950. // Set value
  37951. this.setValue(currentValue);
  37952. // Check events
  37953. var events = this._animation.getEvents();
  37954. for (var index = 0; index < events.length; index++) {
  37955. // Make sure current frame has passed event frame and that event frame is within the current range
  37956. // Also, handle both forward and reverse animations
  37957. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  37958. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  37959. var event = events[index];
  37960. if (!event.isDone) {
  37961. // If event should be done only once, remove it.
  37962. if (event.onlyOnce) {
  37963. events.splice(index, 1);
  37964. index--;
  37965. }
  37966. event.isDone = true;
  37967. event.action();
  37968. } // Don't do anything if the event has already be done.
  37969. }
  37970. else if (events[index].isDone && !events[index].onlyOnce) {
  37971. // reset event, the animation is looping
  37972. events[index].isDone = false;
  37973. }
  37974. }
  37975. if (!returnValue) {
  37976. this._stopped = true;
  37977. }
  37978. return returnValue;
  37979. };
  37980. return RuntimeAnimation;
  37981. }());
  37982. BABYLON.RuntimeAnimation = RuntimeAnimation;
  37983. })(BABYLON || (BABYLON = {}));
  37984. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  37985. var BABYLON;
  37986. (function (BABYLON) {
  37987. var Animatable = (function () {
  37988. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  37989. if (fromFrame === void 0) { fromFrame = 0; }
  37990. if (toFrame === void 0) { toFrame = 100; }
  37991. if (loopAnimation === void 0) { loopAnimation = false; }
  37992. if (speedRatio === void 0) { speedRatio = 1.0; }
  37993. this.target = target;
  37994. this.fromFrame = fromFrame;
  37995. this.toFrame = toFrame;
  37996. this.loopAnimation = loopAnimation;
  37997. this.onAnimationEnd = onAnimationEnd;
  37998. this._localDelayOffset = null;
  37999. this._pausedDelay = null;
  38000. this._runtimeAnimations = new Array();
  38001. this._paused = false;
  38002. this._speedRatio = 1;
  38003. this.animationStarted = false;
  38004. if (animations) {
  38005. this.appendAnimations(target, animations);
  38006. }
  38007. this._speedRatio = speedRatio;
  38008. this._scene = scene;
  38009. scene._activeAnimatables.push(this);
  38010. }
  38011. Object.defineProperty(Animatable.prototype, "speedRatio", {
  38012. get: function () {
  38013. return this._speedRatio;
  38014. },
  38015. set: function (value) {
  38016. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  38017. var animation = this._runtimeAnimations[index];
  38018. animation._prepareForSpeedRatioChange(value);
  38019. }
  38020. this._speedRatio = value;
  38021. },
  38022. enumerable: true,
  38023. configurable: true
  38024. });
  38025. // Methods
  38026. Animatable.prototype.getAnimations = function () {
  38027. return this._runtimeAnimations;
  38028. };
  38029. Animatable.prototype.appendAnimations = function (target, animations) {
  38030. for (var index = 0; index < animations.length; index++) {
  38031. var animation = animations[index];
  38032. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  38033. }
  38034. };
  38035. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  38036. var runtimeAnimations = this._runtimeAnimations;
  38037. for (var index = 0; index < runtimeAnimations.length; index++) {
  38038. if (runtimeAnimations[index].animation.targetProperty === property) {
  38039. return runtimeAnimations[index].animation;
  38040. }
  38041. }
  38042. return null;
  38043. };
  38044. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  38045. var runtimeAnimations = this._runtimeAnimations;
  38046. for (var index = 0; index < runtimeAnimations.length; index++) {
  38047. if (runtimeAnimations[index].animation.targetProperty === property) {
  38048. return runtimeAnimations[index];
  38049. }
  38050. }
  38051. return null;
  38052. };
  38053. Animatable.prototype.reset = function () {
  38054. var runtimeAnimations = this._runtimeAnimations;
  38055. for (var index = 0; index < runtimeAnimations.length; index++) {
  38056. runtimeAnimations[index].reset();
  38057. }
  38058. this._localDelayOffset = null;
  38059. this._pausedDelay = null;
  38060. };
  38061. Animatable.prototype.enableBlending = function (blendingSpeed) {
  38062. var runtimeAnimations = this._runtimeAnimations;
  38063. for (var index = 0; index < runtimeAnimations.length; index++) {
  38064. runtimeAnimations[index].animation.enableBlending = true;
  38065. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  38066. }
  38067. };
  38068. Animatable.prototype.disableBlending = function () {
  38069. var runtimeAnimations = this._runtimeAnimations;
  38070. for (var index = 0; index < runtimeAnimations.length; index++) {
  38071. runtimeAnimations[index].animation.enableBlending = false;
  38072. }
  38073. };
  38074. Animatable.prototype.goToFrame = function (frame) {
  38075. var runtimeAnimations = this._runtimeAnimations;
  38076. if (runtimeAnimations[0]) {
  38077. var fps = runtimeAnimations[0].animation.framePerSecond;
  38078. var currentFrame = runtimeAnimations[0].currentFrame;
  38079. var adjustTime = frame - currentFrame;
  38080. var delay = adjustTime * 1000 / fps;
  38081. this._localDelayOffset -= delay;
  38082. }
  38083. for (var index = 0; index < runtimeAnimations.length; index++) {
  38084. runtimeAnimations[index].goToFrame(frame);
  38085. }
  38086. };
  38087. Animatable.prototype.pause = function () {
  38088. if (this._paused) {
  38089. return;
  38090. }
  38091. this._paused = true;
  38092. };
  38093. Animatable.prototype.restart = function () {
  38094. this._paused = false;
  38095. };
  38096. Animatable.prototype.stop = function (animationName) {
  38097. if (animationName) {
  38098. var idx = this._scene._activeAnimatables.indexOf(this);
  38099. if (idx > -1) {
  38100. var runtimeAnimations = this._runtimeAnimations;
  38101. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  38102. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  38103. continue;
  38104. }
  38105. runtimeAnimations[index].dispose();
  38106. runtimeAnimations.splice(index, 1);
  38107. }
  38108. if (runtimeAnimations.length == 0) {
  38109. this._scene._activeAnimatables.splice(idx, 1);
  38110. if (this.onAnimationEnd) {
  38111. this.onAnimationEnd();
  38112. }
  38113. }
  38114. }
  38115. }
  38116. else {
  38117. var index = this._scene._activeAnimatables.indexOf(this);
  38118. if (index > -1) {
  38119. this._scene._activeAnimatables.splice(index, 1);
  38120. var runtimeAnimations = this._runtimeAnimations;
  38121. for (var index = 0; index < runtimeAnimations.length; index++) {
  38122. runtimeAnimations[index].dispose();
  38123. }
  38124. if (this.onAnimationEnd) {
  38125. this.onAnimationEnd();
  38126. }
  38127. }
  38128. }
  38129. };
  38130. Animatable.prototype._animate = function (delay) {
  38131. if (this._paused) {
  38132. this.animationStarted = false;
  38133. if (this._pausedDelay === null) {
  38134. this._pausedDelay = delay;
  38135. }
  38136. return true;
  38137. }
  38138. if (this._localDelayOffset === null) {
  38139. this._localDelayOffset = delay;
  38140. }
  38141. else if (this._pausedDelay !== null) {
  38142. this._localDelayOffset += delay - this._pausedDelay;
  38143. this._pausedDelay = null;
  38144. }
  38145. // Animating
  38146. var running = false;
  38147. var runtimeAnimations = this._runtimeAnimations;
  38148. var index;
  38149. for (index = 0; index < runtimeAnimations.length; index++) {
  38150. var animation = runtimeAnimations[index];
  38151. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  38152. running = running || isRunning;
  38153. }
  38154. this.animationStarted = running;
  38155. if (!running) {
  38156. // Remove from active animatables
  38157. index = this._scene._activeAnimatables.indexOf(this);
  38158. this._scene._activeAnimatables.splice(index, 1);
  38159. // Dispose all runtime animations
  38160. for (index = 0; index < runtimeAnimations.length; index++) {
  38161. runtimeAnimations[index].dispose();
  38162. }
  38163. }
  38164. if (!running && this.onAnimationEnd) {
  38165. this.onAnimationEnd();
  38166. this.onAnimationEnd = null;
  38167. }
  38168. return running;
  38169. };
  38170. return Animatable;
  38171. }());
  38172. BABYLON.Animatable = Animatable;
  38173. })(BABYLON || (BABYLON = {}));
  38174. //# sourceMappingURL=babylon.animatable.js.map
  38175. var BABYLON;
  38176. (function (BABYLON) {
  38177. var EasingFunction = (function () {
  38178. function EasingFunction() {
  38179. // Properties
  38180. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  38181. }
  38182. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  38183. get: function () {
  38184. return EasingFunction._EASINGMODE_EASEIN;
  38185. },
  38186. enumerable: true,
  38187. configurable: true
  38188. });
  38189. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  38190. get: function () {
  38191. return EasingFunction._EASINGMODE_EASEOUT;
  38192. },
  38193. enumerable: true,
  38194. configurable: true
  38195. });
  38196. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  38197. get: function () {
  38198. return EasingFunction._EASINGMODE_EASEINOUT;
  38199. },
  38200. enumerable: true,
  38201. configurable: true
  38202. });
  38203. EasingFunction.prototype.setEasingMode = function (easingMode) {
  38204. var n = Math.min(Math.max(easingMode, 0), 2);
  38205. this._easingMode = n;
  38206. };
  38207. EasingFunction.prototype.getEasingMode = function () {
  38208. return this._easingMode;
  38209. };
  38210. EasingFunction.prototype.easeInCore = function (gradient) {
  38211. throw new Error('You must implement this method');
  38212. };
  38213. EasingFunction.prototype.ease = function (gradient) {
  38214. switch (this._easingMode) {
  38215. case EasingFunction.EASINGMODE_EASEIN:
  38216. return this.easeInCore(gradient);
  38217. case EasingFunction.EASINGMODE_EASEOUT:
  38218. return (1 - this.easeInCore(1 - gradient));
  38219. }
  38220. if (gradient >= 0.5) {
  38221. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  38222. }
  38223. return (this.easeInCore(gradient * 2) * 0.5);
  38224. };
  38225. return EasingFunction;
  38226. }());
  38227. //Statics
  38228. EasingFunction._EASINGMODE_EASEIN = 0;
  38229. EasingFunction._EASINGMODE_EASEOUT = 1;
  38230. EasingFunction._EASINGMODE_EASEINOUT = 2;
  38231. BABYLON.EasingFunction = EasingFunction;
  38232. var CircleEase = (function (_super) {
  38233. __extends(CircleEase, _super);
  38234. function CircleEase() {
  38235. return _super !== null && _super.apply(this, arguments) || this;
  38236. }
  38237. CircleEase.prototype.easeInCore = function (gradient) {
  38238. gradient = Math.max(0, Math.min(1, gradient));
  38239. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  38240. };
  38241. return CircleEase;
  38242. }(EasingFunction));
  38243. BABYLON.CircleEase = CircleEase;
  38244. var BackEase = (function (_super) {
  38245. __extends(BackEase, _super);
  38246. function BackEase(amplitude) {
  38247. if (amplitude === void 0) { amplitude = 1; }
  38248. var _this = _super.call(this) || this;
  38249. _this.amplitude = amplitude;
  38250. return _this;
  38251. }
  38252. BackEase.prototype.easeInCore = function (gradient) {
  38253. var num = Math.max(0, this.amplitude);
  38254. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  38255. };
  38256. return BackEase;
  38257. }(EasingFunction));
  38258. BABYLON.BackEase = BackEase;
  38259. var BounceEase = (function (_super) {
  38260. __extends(BounceEase, _super);
  38261. function BounceEase(bounces, bounciness) {
  38262. if (bounces === void 0) { bounces = 3; }
  38263. if (bounciness === void 0) { bounciness = 2; }
  38264. var _this = _super.call(this) || this;
  38265. _this.bounces = bounces;
  38266. _this.bounciness = bounciness;
  38267. return _this;
  38268. }
  38269. BounceEase.prototype.easeInCore = function (gradient) {
  38270. var y = Math.max(0.0, this.bounces);
  38271. var bounciness = this.bounciness;
  38272. if (bounciness <= 1.0) {
  38273. bounciness = 1.001;
  38274. }
  38275. var num9 = Math.pow(bounciness, y);
  38276. var num5 = 1.0 - bounciness;
  38277. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  38278. var num15 = gradient * num4;
  38279. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  38280. var num3 = Math.floor(num65);
  38281. var num13 = num3 + 1.0;
  38282. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  38283. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  38284. var num7 = (num8 + num12) * 0.5;
  38285. var num6 = gradient - num7;
  38286. var num2 = num7 - num8;
  38287. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  38288. };
  38289. return BounceEase;
  38290. }(EasingFunction));
  38291. BABYLON.BounceEase = BounceEase;
  38292. var CubicEase = (function (_super) {
  38293. __extends(CubicEase, _super);
  38294. function CubicEase() {
  38295. return _super !== null && _super.apply(this, arguments) || this;
  38296. }
  38297. CubicEase.prototype.easeInCore = function (gradient) {
  38298. return (gradient * gradient * gradient);
  38299. };
  38300. return CubicEase;
  38301. }(EasingFunction));
  38302. BABYLON.CubicEase = CubicEase;
  38303. var ElasticEase = (function (_super) {
  38304. __extends(ElasticEase, _super);
  38305. function ElasticEase(oscillations, springiness) {
  38306. if (oscillations === void 0) { oscillations = 3; }
  38307. if (springiness === void 0) { springiness = 3; }
  38308. var _this = _super.call(this) || this;
  38309. _this.oscillations = oscillations;
  38310. _this.springiness = springiness;
  38311. return _this;
  38312. }
  38313. ElasticEase.prototype.easeInCore = function (gradient) {
  38314. var num2;
  38315. var num3 = Math.max(0.0, this.oscillations);
  38316. var num = Math.max(0.0, this.springiness);
  38317. if (num == 0) {
  38318. num2 = gradient;
  38319. }
  38320. else {
  38321. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  38322. }
  38323. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  38324. };
  38325. return ElasticEase;
  38326. }(EasingFunction));
  38327. BABYLON.ElasticEase = ElasticEase;
  38328. var ExponentialEase = (function (_super) {
  38329. __extends(ExponentialEase, _super);
  38330. function ExponentialEase(exponent) {
  38331. if (exponent === void 0) { exponent = 2; }
  38332. var _this = _super.call(this) || this;
  38333. _this.exponent = exponent;
  38334. return _this;
  38335. }
  38336. ExponentialEase.prototype.easeInCore = function (gradient) {
  38337. if (this.exponent <= 0) {
  38338. return gradient;
  38339. }
  38340. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  38341. };
  38342. return ExponentialEase;
  38343. }(EasingFunction));
  38344. BABYLON.ExponentialEase = ExponentialEase;
  38345. var PowerEase = (function (_super) {
  38346. __extends(PowerEase, _super);
  38347. function PowerEase(power) {
  38348. if (power === void 0) { power = 2; }
  38349. var _this = _super.call(this) || this;
  38350. _this.power = power;
  38351. return _this;
  38352. }
  38353. PowerEase.prototype.easeInCore = function (gradient) {
  38354. var y = Math.max(0.0, this.power);
  38355. return Math.pow(gradient, y);
  38356. };
  38357. return PowerEase;
  38358. }(EasingFunction));
  38359. BABYLON.PowerEase = PowerEase;
  38360. var QuadraticEase = (function (_super) {
  38361. __extends(QuadraticEase, _super);
  38362. function QuadraticEase() {
  38363. return _super !== null && _super.apply(this, arguments) || this;
  38364. }
  38365. QuadraticEase.prototype.easeInCore = function (gradient) {
  38366. return (gradient * gradient);
  38367. };
  38368. return QuadraticEase;
  38369. }(EasingFunction));
  38370. BABYLON.QuadraticEase = QuadraticEase;
  38371. var QuarticEase = (function (_super) {
  38372. __extends(QuarticEase, _super);
  38373. function QuarticEase() {
  38374. return _super !== null && _super.apply(this, arguments) || this;
  38375. }
  38376. QuarticEase.prototype.easeInCore = function (gradient) {
  38377. return (gradient * gradient * gradient * gradient);
  38378. };
  38379. return QuarticEase;
  38380. }(EasingFunction));
  38381. BABYLON.QuarticEase = QuarticEase;
  38382. var QuinticEase = (function (_super) {
  38383. __extends(QuinticEase, _super);
  38384. function QuinticEase() {
  38385. return _super !== null && _super.apply(this, arguments) || this;
  38386. }
  38387. QuinticEase.prototype.easeInCore = function (gradient) {
  38388. return (gradient * gradient * gradient * gradient * gradient);
  38389. };
  38390. return QuinticEase;
  38391. }(EasingFunction));
  38392. BABYLON.QuinticEase = QuinticEase;
  38393. var SineEase = (function (_super) {
  38394. __extends(SineEase, _super);
  38395. function SineEase() {
  38396. return _super !== null && _super.apply(this, arguments) || this;
  38397. }
  38398. SineEase.prototype.easeInCore = function (gradient) {
  38399. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  38400. };
  38401. return SineEase;
  38402. }(EasingFunction));
  38403. BABYLON.SineEase = SineEase;
  38404. var BezierCurveEase = (function (_super) {
  38405. __extends(BezierCurveEase, _super);
  38406. function BezierCurveEase(x1, y1, x2, y2) {
  38407. if (x1 === void 0) { x1 = 0; }
  38408. if (y1 === void 0) { y1 = 0; }
  38409. if (x2 === void 0) { x2 = 1; }
  38410. if (y2 === void 0) { y2 = 1; }
  38411. var _this = _super.call(this) || this;
  38412. _this.x1 = x1;
  38413. _this.y1 = y1;
  38414. _this.x2 = x2;
  38415. _this.y2 = y2;
  38416. return _this;
  38417. }
  38418. BezierCurveEase.prototype.easeInCore = function (gradient) {
  38419. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  38420. };
  38421. return BezierCurveEase;
  38422. }(EasingFunction));
  38423. BABYLON.BezierCurveEase = BezierCurveEase;
  38424. })(BABYLON || (BABYLON = {}));
  38425. //# sourceMappingURL=babylon.easing.js.map
  38426. var BABYLON;
  38427. (function (BABYLON) {
  38428. var Condition = (function () {
  38429. function Condition(actionManager) {
  38430. this._actionManager = actionManager;
  38431. }
  38432. Condition.prototype.isValid = function () {
  38433. return true;
  38434. };
  38435. Condition.prototype._getProperty = function (propertyPath) {
  38436. return this._actionManager._getProperty(propertyPath);
  38437. };
  38438. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  38439. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38440. };
  38441. Condition.prototype.serialize = function () {
  38442. };
  38443. Condition.prototype._serialize = function (serializedCondition) {
  38444. return {
  38445. type: 2,
  38446. children: [],
  38447. name: serializedCondition.name,
  38448. properties: serializedCondition.properties
  38449. };
  38450. };
  38451. return Condition;
  38452. }());
  38453. BABYLON.Condition = Condition;
  38454. var ValueCondition = (function (_super) {
  38455. __extends(ValueCondition, _super);
  38456. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  38457. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  38458. var _this = _super.call(this, actionManager) || this;
  38459. _this.propertyPath = propertyPath;
  38460. _this.value = value;
  38461. _this.operator = operator;
  38462. _this._target = target;
  38463. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  38464. _this._property = _this._getProperty(_this.propertyPath);
  38465. return _this;
  38466. }
  38467. Object.defineProperty(ValueCondition, "IsEqual", {
  38468. get: function () {
  38469. return ValueCondition._IsEqual;
  38470. },
  38471. enumerable: true,
  38472. configurable: true
  38473. });
  38474. Object.defineProperty(ValueCondition, "IsDifferent", {
  38475. get: function () {
  38476. return ValueCondition._IsDifferent;
  38477. },
  38478. enumerable: true,
  38479. configurable: true
  38480. });
  38481. Object.defineProperty(ValueCondition, "IsGreater", {
  38482. get: function () {
  38483. return ValueCondition._IsGreater;
  38484. },
  38485. enumerable: true,
  38486. configurable: true
  38487. });
  38488. Object.defineProperty(ValueCondition, "IsLesser", {
  38489. get: function () {
  38490. return ValueCondition._IsLesser;
  38491. },
  38492. enumerable: true,
  38493. configurable: true
  38494. });
  38495. // Methods
  38496. ValueCondition.prototype.isValid = function () {
  38497. switch (this.operator) {
  38498. case ValueCondition.IsGreater:
  38499. return this._effectiveTarget[this._property] > this.value;
  38500. case ValueCondition.IsLesser:
  38501. return this._effectiveTarget[this._property] < this.value;
  38502. case ValueCondition.IsEqual:
  38503. case ValueCondition.IsDifferent:
  38504. var check;
  38505. if (this.value.equals) {
  38506. check = this.value.equals(this._effectiveTarget[this._property]);
  38507. }
  38508. else {
  38509. check = this.value === this._effectiveTarget[this._property];
  38510. }
  38511. return this.operator === ValueCondition.IsEqual ? check : !check;
  38512. }
  38513. return false;
  38514. };
  38515. ValueCondition.prototype.serialize = function () {
  38516. return this._serialize({
  38517. name: "ValueCondition",
  38518. properties: [
  38519. BABYLON.Action._GetTargetProperty(this._target),
  38520. { name: "propertyPath", value: this.propertyPath },
  38521. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38522. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  38523. ]
  38524. });
  38525. };
  38526. ValueCondition.GetOperatorName = function (operator) {
  38527. switch (operator) {
  38528. case ValueCondition._IsEqual: return "IsEqual";
  38529. case ValueCondition._IsDifferent: return "IsDifferent";
  38530. case ValueCondition._IsGreater: return "IsGreater";
  38531. case ValueCondition._IsLesser: return "IsLesser";
  38532. default: return "";
  38533. }
  38534. };
  38535. return ValueCondition;
  38536. }(Condition));
  38537. // Statics
  38538. ValueCondition._IsEqual = 0;
  38539. ValueCondition._IsDifferent = 1;
  38540. ValueCondition._IsGreater = 2;
  38541. ValueCondition._IsLesser = 3;
  38542. BABYLON.ValueCondition = ValueCondition;
  38543. var PredicateCondition = (function (_super) {
  38544. __extends(PredicateCondition, _super);
  38545. function PredicateCondition(actionManager, predicate) {
  38546. var _this = _super.call(this, actionManager) || this;
  38547. _this.predicate = predicate;
  38548. return _this;
  38549. }
  38550. PredicateCondition.prototype.isValid = function () {
  38551. return this.predicate();
  38552. };
  38553. return PredicateCondition;
  38554. }(Condition));
  38555. BABYLON.PredicateCondition = PredicateCondition;
  38556. var StateCondition = (function (_super) {
  38557. __extends(StateCondition, _super);
  38558. function StateCondition(actionManager, target, value) {
  38559. var _this = _super.call(this, actionManager) || this;
  38560. _this.value = value;
  38561. _this._target = target;
  38562. return _this;
  38563. }
  38564. // Methods
  38565. StateCondition.prototype.isValid = function () {
  38566. return this._target.state === this.value;
  38567. };
  38568. StateCondition.prototype.serialize = function () {
  38569. return this._serialize({
  38570. name: "StateCondition",
  38571. properties: [
  38572. BABYLON.Action._GetTargetProperty(this._target),
  38573. { name: "value", value: this.value }
  38574. ]
  38575. });
  38576. };
  38577. return StateCondition;
  38578. }(Condition));
  38579. BABYLON.StateCondition = StateCondition;
  38580. })(BABYLON || (BABYLON = {}));
  38581. //# sourceMappingURL=babylon.condition.js.map
  38582. var BABYLON;
  38583. (function (BABYLON) {
  38584. var Action = (function () {
  38585. function Action(triggerOptions, condition) {
  38586. this.triggerOptions = triggerOptions;
  38587. this.onBeforeExecuteObservable = new BABYLON.Observable();
  38588. if (triggerOptions.parameter) {
  38589. this.trigger = triggerOptions.trigger;
  38590. this._triggerParameter = triggerOptions.parameter;
  38591. }
  38592. else {
  38593. this.trigger = triggerOptions;
  38594. }
  38595. this._nextActiveAction = this;
  38596. this._condition = condition;
  38597. }
  38598. // Methods
  38599. Action.prototype._prepare = function () {
  38600. };
  38601. Action.prototype.getTriggerParameter = function () {
  38602. return this._triggerParameter;
  38603. };
  38604. Action.prototype._executeCurrent = function (evt) {
  38605. if (this._nextActiveAction._condition) {
  38606. var condition = this._nextActiveAction._condition;
  38607. var currentRenderId = this._actionManager.getScene().getRenderId();
  38608. // We cache the current evaluation for the current frame
  38609. if (condition._evaluationId === currentRenderId) {
  38610. if (!condition._currentResult) {
  38611. return;
  38612. }
  38613. }
  38614. else {
  38615. condition._evaluationId = currentRenderId;
  38616. if (!condition.isValid()) {
  38617. condition._currentResult = false;
  38618. return;
  38619. }
  38620. condition._currentResult = true;
  38621. }
  38622. }
  38623. this.onBeforeExecuteObservable.notifyObservers(this);
  38624. this._nextActiveAction.execute(evt);
  38625. this.skipToNextActiveAction();
  38626. };
  38627. Action.prototype.execute = function (evt) {
  38628. };
  38629. Action.prototype.skipToNextActiveAction = function () {
  38630. if (this._nextActiveAction._child) {
  38631. if (!this._nextActiveAction._child._actionManager) {
  38632. this._nextActiveAction._child._actionManager = this._actionManager;
  38633. }
  38634. this._nextActiveAction = this._nextActiveAction._child;
  38635. }
  38636. else {
  38637. this._nextActiveAction = this;
  38638. }
  38639. };
  38640. Action.prototype.then = function (action) {
  38641. this._child = action;
  38642. action._actionManager = this._actionManager;
  38643. action._prepare();
  38644. return action;
  38645. };
  38646. Action.prototype._getProperty = function (propertyPath) {
  38647. return this._actionManager._getProperty(propertyPath);
  38648. };
  38649. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  38650. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38651. };
  38652. Action.prototype.serialize = function (parent) {
  38653. };
  38654. // Called by BABYLON.Action objects in serialize(...). Internal use
  38655. Action.prototype._serialize = function (serializedAction, parent) {
  38656. var serializationObject = {
  38657. type: 1,
  38658. children: [],
  38659. name: serializedAction.name,
  38660. properties: serializedAction.properties || []
  38661. };
  38662. // Serialize child
  38663. if (this._child) {
  38664. this._child.serialize(serializationObject);
  38665. }
  38666. // Check if "this" has a condition
  38667. if (this._condition) {
  38668. var serializedCondition = this._condition.serialize();
  38669. serializedCondition.children.push(serializationObject);
  38670. if (parent) {
  38671. parent.children.push(serializedCondition);
  38672. }
  38673. return serializedCondition;
  38674. }
  38675. if (parent) {
  38676. parent.children.push(serializationObject);
  38677. }
  38678. return serializationObject;
  38679. };
  38680. return Action;
  38681. }());
  38682. Action._SerializeValueAsString = function (value) {
  38683. if (typeof value === "number") {
  38684. return value.toString();
  38685. }
  38686. if (typeof value === "boolean") {
  38687. return value ? "true" : "false";
  38688. }
  38689. if (value instanceof BABYLON.Vector2) {
  38690. return value.x + ", " + value.y;
  38691. }
  38692. if (value instanceof BABYLON.Vector3) {
  38693. return value.x + ", " + value.y + ", " + value.z;
  38694. }
  38695. if (value instanceof BABYLON.Color3) {
  38696. return value.r + ", " + value.g + ", " + value.b;
  38697. }
  38698. if (value instanceof BABYLON.Color4) {
  38699. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  38700. }
  38701. return value; // string
  38702. };
  38703. Action._GetTargetProperty = function (target) {
  38704. return {
  38705. name: "target",
  38706. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  38707. : target instanceof BABYLON.Light ? "LightProperties"
  38708. : target instanceof BABYLON.Camera ? "CameraProperties"
  38709. : "SceneProperties",
  38710. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  38711. };
  38712. };
  38713. BABYLON.Action = Action;
  38714. })(BABYLON || (BABYLON = {}));
  38715. //# sourceMappingURL=babylon.action.js.map
  38716. var BABYLON;
  38717. (function (BABYLON) {
  38718. /**
  38719. * ActionEvent is the event beint sent when an action is triggered.
  38720. */
  38721. var ActionEvent = (function () {
  38722. /**
  38723. * @param source The mesh or sprite that triggered the action.
  38724. * @param pointerX The X mouse cursor position at the time of the event
  38725. * @param pointerY The Y mouse cursor position at the time of the event
  38726. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  38727. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  38728. */
  38729. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  38730. this.source = source;
  38731. this.pointerX = pointerX;
  38732. this.pointerY = pointerY;
  38733. this.meshUnderPointer = meshUnderPointer;
  38734. this.sourceEvent = sourceEvent;
  38735. this.additionalData = additionalData;
  38736. }
  38737. /**
  38738. * Helper function to auto-create an ActionEvent from a source mesh.
  38739. * @param source The source mesh that triggered the event
  38740. * @param evt {Event} The original (browser) event
  38741. */
  38742. ActionEvent.CreateNew = function (source, evt, additionalData) {
  38743. var scene = source.getScene();
  38744. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38745. };
  38746. /**
  38747. * Helper function to auto-create an ActionEvent from a source mesh.
  38748. * @param source The source sprite that triggered the event
  38749. * @param scene Scene associated with the sprite
  38750. * @param evt {Event} The original (browser) event
  38751. */
  38752. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  38753. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38754. };
  38755. /**
  38756. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  38757. * @param scene the scene where the event occurred
  38758. * @param evt {Event} The original (browser) event
  38759. */
  38760. ActionEvent.CreateNewFromScene = function (scene, evt) {
  38761. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  38762. };
  38763. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  38764. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  38765. };
  38766. return ActionEvent;
  38767. }());
  38768. BABYLON.ActionEvent = ActionEvent;
  38769. /**
  38770. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  38771. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  38772. */
  38773. var ActionManager = (function () {
  38774. function ActionManager(scene) {
  38775. // Members
  38776. this.actions = new Array();
  38777. this.hoverCursor = '';
  38778. this._scene = scene;
  38779. scene._actionManagers.push(this);
  38780. }
  38781. Object.defineProperty(ActionManager, "NothingTrigger", {
  38782. get: function () {
  38783. return ActionManager._NothingTrigger;
  38784. },
  38785. enumerable: true,
  38786. configurable: true
  38787. });
  38788. Object.defineProperty(ActionManager, "OnPickTrigger", {
  38789. get: function () {
  38790. return ActionManager._OnPickTrigger;
  38791. },
  38792. enumerable: true,
  38793. configurable: true
  38794. });
  38795. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  38796. get: function () {
  38797. return ActionManager._OnLeftPickTrigger;
  38798. },
  38799. enumerable: true,
  38800. configurable: true
  38801. });
  38802. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  38803. get: function () {
  38804. return ActionManager._OnRightPickTrigger;
  38805. },
  38806. enumerable: true,
  38807. configurable: true
  38808. });
  38809. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  38810. get: function () {
  38811. return ActionManager._OnCenterPickTrigger;
  38812. },
  38813. enumerable: true,
  38814. configurable: true
  38815. });
  38816. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  38817. get: function () {
  38818. return ActionManager._OnPickDownTrigger;
  38819. },
  38820. enumerable: true,
  38821. configurable: true
  38822. });
  38823. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  38824. get: function () {
  38825. return ActionManager._OnDoublePickTrigger;
  38826. },
  38827. enumerable: true,
  38828. configurable: true
  38829. });
  38830. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  38831. get: function () {
  38832. return ActionManager._OnPickUpTrigger;
  38833. },
  38834. enumerable: true,
  38835. configurable: true
  38836. });
  38837. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  38838. /// This trigger will only be raised if you also declared a OnPickDown
  38839. get: function () {
  38840. return ActionManager._OnPickOutTrigger;
  38841. },
  38842. enumerable: true,
  38843. configurable: true
  38844. });
  38845. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  38846. get: function () {
  38847. return ActionManager._OnLongPressTrigger;
  38848. },
  38849. enumerable: true,
  38850. configurable: true
  38851. });
  38852. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  38853. get: function () {
  38854. return ActionManager._OnPointerOverTrigger;
  38855. },
  38856. enumerable: true,
  38857. configurable: true
  38858. });
  38859. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  38860. get: function () {
  38861. return ActionManager._OnPointerOutTrigger;
  38862. },
  38863. enumerable: true,
  38864. configurable: true
  38865. });
  38866. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  38867. get: function () {
  38868. return ActionManager._OnEveryFrameTrigger;
  38869. },
  38870. enumerable: true,
  38871. configurable: true
  38872. });
  38873. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  38874. get: function () {
  38875. return ActionManager._OnIntersectionEnterTrigger;
  38876. },
  38877. enumerable: true,
  38878. configurable: true
  38879. });
  38880. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  38881. get: function () {
  38882. return ActionManager._OnIntersectionExitTrigger;
  38883. },
  38884. enumerable: true,
  38885. configurable: true
  38886. });
  38887. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  38888. get: function () {
  38889. return ActionManager._OnKeyDownTrigger;
  38890. },
  38891. enumerable: true,
  38892. configurable: true
  38893. });
  38894. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  38895. get: function () {
  38896. return ActionManager._OnKeyUpTrigger;
  38897. },
  38898. enumerable: true,
  38899. configurable: true
  38900. });
  38901. // Methods
  38902. ActionManager.prototype.dispose = function () {
  38903. var index = this._scene._actionManagers.indexOf(this);
  38904. for (var i = 0; i < this.actions.length; i++) {
  38905. var action = this.actions[i];
  38906. ActionManager.Triggers[action.trigger]--;
  38907. if (ActionManager.Triggers[action.trigger] === 0) {
  38908. delete ActionManager.Triggers[action.trigger];
  38909. }
  38910. }
  38911. if (index > -1) {
  38912. this._scene._actionManagers.splice(index, 1);
  38913. }
  38914. };
  38915. ActionManager.prototype.getScene = function () {
  38916. return this._scene;
  38917. };
  38918. /**
  38919. * Does this action manager handles actions of any of the given triggers
  38920. * @param {number[]} triggers - the triggers to be tested
  38921. * @return {boolean} whether one (or more) of the triggers is handeled
  38922. */
  38923. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  38924. for (var index = 0; index < this.actions.length; index++) {
  38925. var action = this.actions[index];
  38926. if (triggers.indexOf(action.trigger) > -1) {
  38927. return true;
  38928. }
  38929. }
  38930. return false;
  38931. };
  38932. /**
  38933. * Does this action manager handles actions of a given trigger
  38934. * @param {number} trigger - the trigger to be tested
  38935. * @return {boolean} whether the trigger is handeled
  38936. */
  38937. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  38938. for (var index = 0; index < this.actions.length; index++) {
  38939. var action = this.actions[index];
  38940. if (action.trigger === trigger) {
  38941. return true;
  38942. }
  38943. }
  38944. return false;
  38945. };
  38946. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  38947. /**
  38948. * Does this action manager has pointer triggers
  38949. * @return {boolean} whether or not it has pointer triggers
  38950. */
  38951. get: function () {
  38952. for (var index = 0; index < this.actions.length; index++) {
  38953. var action = this.actions[index];
  38954. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  38955. return true;
  38956. }
  38957. }
  38958. return false;
  38959. },
  38960. enumerable: true,
  38961. configurable: true
  38962. });
  38963. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  38964. /**
  38965. * Does this action manager has pick triggers
  38966. * @return {boolean} whether or not it has pick triggers
  38967. */
  38968. get: function () {
  38969. for (var index = 0; index < this.actions.length; index++) {
  38970. var action = this.actions[index];
  38971. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  38972. return true;
  38973. }
  38974. }
  38975. return false;
  38976. },
  38977. enumerable: true,
  38978. configurable: true
  38979. });
  38980. Object.defineProperty(ActionManager, "HasTriggers", {
  38981. /**
  38982. * Does exist one action manager with at least one trigger
  38983. * @return {boolean} whether or not it exists one action manager with one trigger
  38984. **/
  38985. get: function () {
  38986. for (var t in ActionManager.Triggers) {
  38987. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38988. return true;
  38989. }
  38990. }
  38991. return false;
  38992. },
  38993. enumerable: true,
  38994. configurable: true
  38995. });
  38996. Object.defineProperty(ActionManager, "HasPickTriggers", {
  38997. /**
  38998. * Does exist one action manager with at least one pick trigger
  38999. * @return {boolean} whether or not it exists one action manager with one pick trigger
  39000. **/
  39001. get: function () {
  39002. for (var t in ActionManager.Triggers) {
  39003. if (ActionManager.Triggers.hasOwnProperty(t)) {
  39004. var t_int = parseInt(t);
  39005. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  39006. return true;
  39007. }
  39008. }
  39009. }
  39010. return false;
  39011. },
  39012. enumerable: true,
  39013. configurable: true
  39014. });
  39015. /**
  39016. * Does exist one action manager that handles actions of a given trigger
  39017. * @param {number} trigger - the trigger to be tested
  39018. * @return {boolean} whether the trigger is handeled by at least one action manager
  39019. **/
  39020. ActionManager.HasSpecificTrigger = function (trigger) {
  39021. for (var t in ActionManager.Triggers) {
  39022. if (ActionManager.Triggers.hasOwnProperty(t)) {
  39023. var t_int = parseInt(t);
  39024. if (t_int === trigger) {
  39025. return true;
  39026. }
  39027. }
  39028. }
  39029. return false;
  39030. };
  39031. /**
  39032. * Registers an action to this action manager
  39033. * @param {BABYLON.Action} action - the action to be registered
  39034. * @return {BABYLON.Action} the action amended (prepared) after registration
  39035. */
  39036. ActionManager.prototype.registerAction = function (action) {
  39037. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  39038. if (this.getScene().actionManager !== this) {
  39039. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  39040. return null;
  39041. }
  39042. }
  39043. this.actions.push(action);
  39044. if (ActionManager.Triggers[action.trigger]) {
  39045. ActionManager.Triggers[action.trigger]++;
  39046. }
  39047. else {
  39048. ActionManager.Triggers[action.trigger] = 1;
  39049. }
  39050. action._actionManager = this;
  39051. action._prepare();
  39052. return action;
  39053. };
  39054. /**
  39055. * Process a specific trigger
  39056. * @param {number} trigger - the trigger to process
  39057. * @param evt {BABYLON.ActionEvent} the event details to be processed
  39058. */
  39059. ActionManager.prototype.processTrigger = function (trigger, evt) {
  39060. for (var index = 0; index < this.actions.length; index++) {
  39061. var action = this.actions[index];
  39062. if (action.trigger === trigger) {
  39063. if (trigger === ActionManager.OnKeyUpTrigger
  39064. || trigger === ActionManager.OnKeyDownTrigger) {
  39065. var parameter = action.getTriggerParameter();
  39066. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  39067. if (!parameter.toLowerCase) {
  39068. continue;
  39069. }
  39070. var lowerCase = parameter.toLowerCase();
  39071. if (lowerCase !== evt.sourceEvent.key) {
  39072. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  39073. var actualkey = String.fromCharCode(unicode).toLowerCase();
  39074. if (actualkey !== lowerCase) {
  39075. continue;
  39076. }
  39077. }
  39078. }
  39079. }
  39080. action._executeCurrent(evt);
  39081. }
  39082. }
  39083. };
  39084. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  39085. var properties = propertyPath.split(".");
  39086. for (var index = 0; index < properties.length - 1; index++) {
  39087. target = target[properties[index]];
  39088. }
  39089. return target;
  39090. };
  39091. ActionManager.prototype._getProperty = function (propertyPath) {
  39092. var properties = propertyPath.split(".");
  39093. return properties[properties.length - 1];
  39094. };
  39095. ActionManager.prototype.serialize = function (name) {
  39096. var root = {
  39097. children: [],
  39098. name: name,
  39099. type: 3,
  39100. properties: [] // Empty for root but required
  39101. };
  39102. for (var i = 0; i < this.actions.length; i++) {
  39103. var triggerObject = {
  39104. type: 0,
  39105. children: [],
  39106. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  39107. properties: []
  39108. };
  39109. var triggerOptions = this.actions[i].triggerOptions;
  39110. if (triggerOptions && typeof triggerOptions !== "number") {
  39111. if (triggerOptions.parameter instanceof BABYLON.Node) {
  39112. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  39113. }
  39114. else {
  39115. var parameter = {};
  39116. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  39117. if (triggerOptions.parameter.mesh) {
  39118. parameter._meshId = triggerOptions.parameter.mesh.id;
  39119. }
  39120. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  39121. }
  39122. }
  39123. // Serialize child action, recursively
  39124. this.actions[i].serialize(triggerObject);
  39125. // Add serialized trigger
  39126. root.children.push(triggerObject);
  39127. }
  39128. return root;
  39129. };
  39130. ActionManager.Parse = function (parsedActions, object, scene) {
  39131. var actionManager = new BABYLON.ActionManager(scene);
  39132. if (object === null)
  39133. scene.actionManager = actionManager;
  39134. else
  39135. object.actionManager = actionManager;
  39136. // instanciate a new object
  39137. var instanciate = function (name, params) {
  39138. var newInstance = Object.create(BABYLON[name].prototype);
  39139. newInstance.constructor.apply(newInstance, params);
  39140. return newInstance;
  39141. };
  39142. var parseParameter = function (name, value, target, propertyPath) {
  39143. if (propertyPath === null) {
  39144. // String, boolean or float
  39145. var floatValue = parseFloat(value);
  39146. if (value === "true" || value === "false")
  39147. return value === "true";
  39148. else
  39149. return isNaN(floatValue) ? value : floatValue;
  39150. }
  39151. var effectiveTarget = propertyPath.split(".");
  39152. var values = value.split(",");
  39153. // Get effective Target
  39154. for (var i = 0; i < effectiveTarget.length; i++) {
  39155. target = target[effectiveTarget[i]];
  39156. }
  39157. // Return appropriate value with its type
  39158. if (typeof (target) === "boolean")
  39159. return values[0] === "true";
  39160. if (typeof (target) === "string")
  39161. return values[0];
  39162. // Parameters with multiple values such as Vector3 etc.
  39163. var split = new Array();
  39164. for (var i = 0; i < values.length; i++)
  39165. split.push(parseFloat(values[i]));
  39166. if (target instanceof BABYLON.Vector3)
  39167. return BABYLON.Vector3.FromArray(split);
  39168. if (target instanceof BABYLON.Vector4)
  39169. return BABYLON.Vector4.FromArray(split);
  39170. if (target instanceof BABYLON.Color3)
  39171. return BABYLON.Color3.FromArray(split);
  39172. if (target instanceof BABYLON.Color4)
  39173. return BABYLON.Color4.FromArray(split);
  39174. return parseFloat(values[0]);
  39175. };
  39176. // traverse graph per trigger
  39177. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  39178. if (combineArray === void 0) { combineArray = null; }
  39179. if (parsedAction.detached)
  39180. return;
  39181. var parameters = new Array();
  39182. var target = null;
  39183. var propertyPath = null;
  39184. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  39185. // Parameters
  39186. if (parsedAction.type === 2)
  39187. parameters.push(actionManager);
  39188. else
  39189. parameters.push(trigger);
  39190. if (combine) {
  39191. var actions = new Array();
  39192. for (var j = 0; j < parsedAction.combine.length; j++) {
  39193. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  39194. }
  39195. parameters.push(actions);
  39196. }
  39197. else {
  39198. for (var i = 0; i < parsedAction.properties.length; i++) {
  39199. var value = parsedAction.properties[i].value;
  39200. var name = parsedAction.properties[i].name;
  39201. var targetType = parsedAction.properties[i].targetType;
  39202. if (name === "target")
  39203. if (targetType !== null && targetType === "SceneProperties")
  39204. value = target = scene;
  39205. else
  39206. value = target = scene.getNodeByName(value);
  39207. else if (name === "parent")
  39208. value = scene.getNodeByName(value);
  39209. else if (name === "sound")
  39210. value = scene.getSoundByName(value);
  39211. else if (name !== "propertyPath") {
  39212. if (parsedAction.type === 2 && name === "operator")
  39213. value = BABYLON.ValueCondition[value];
  39214. else
  39215. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  39216. }
  39217. else {
  39218. propertyPath = value;
  39219. }
  39220. parameters.push(value);
  39221. }
  39222. }
  39223. if (combineArray === null) {
  39224. parameters.push(condition);
  39225. }
  39226. else {
  39227. parameters.push(null);
  39228. }
  39229. // If interpolate value action
  39230. if (parsedAction.name === "InterpolateValueAction") {
  39231. var param = parameters[parameters.length - 2];
  39232. parameters[parameters.length - 1] = param;
  39233. parameters[parameters.length - 2] = condition;
  39234. }
  39235. // Action or condition(s) and not CombineAction
  39236. var newAction = instanciate(parsedAction.name, parameters);
  39237. if (newAction instanceof BABYLON.Condition && condition !== null) {
  39238. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  39239. if (action)
  39240. action.then(nothing);
  39241. else
  39242. actionManager.registerAction(nothing);
  39243. action = nothing;
  39244. }
  39245. if (combineArray === null) {
  39246. if (newAction instanceof BABYLON.Condition) {
  39247. condition = newAction;
  39248. newAction = action;
  39249. }
  39250. else {
  39251. condition = null;
  39252. if (action)
  39253. action.then(newAction);
  39254. else
  39255. actionManager.registerAction(newAction);
  39256. }
  39257. }
  39258. else {
  39259. combineArray.push(newAction);
  39260. }
  39261. for (var i = 0; i < parsedAction.children.length; i++)
  39262. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  39263. };
  39264. // triggers
  39265. for (var i = 0; i < parsedActions.children.length; i++) {
  39266. var triggerParams;
  39267. var trigger = parsedActions.children[i];
  39268. if (trigger.properties.length > 0) {
  39269. var param = trigger.properties[0].value;
  39270. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  39271. if (value._meshId) {
  39272. value.mesh = scene.getMeshByID(value._meshId);
  39273. }
  39274. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  39275. }
  39276. else
  39277. triggerParams = BABYLON.ActionManager[trigger.name];
  39278. for (var j = 0; j < trigger.children.length; j++) {
  39279. if (!trigger.detached)
  39280. traverse(trigger.children[j], triggerParams, null, null);
  39281. }
  39282. }
  39283. };
  39284. ActionManager.GetTriggerName = function (trigger) {
  39285. switch (trigger) {
  39286. case 0: return "NothingTrigger";
  39287. case 1: return "OnPickTrigger";
  39288. case 2: return "OnLeftPickTrigger";
  39289. case 3: return "OnRightPickTrigger";
  39290. case 4: return "OnCenterPickTrigger";
  39291. case 5: return "OnPickDownTrigger";
  39292. case 6: return "OnPickUpTrigger";
  39293. case 7: return "OnLongPressTrigger";
  39294. case 8: return "OnPointerOverTrigger";
  39295. case 9: return "OnPointerOutTrigger";
  39296. case 10: return "OnEveryFrameTrigger";
  39297. case 11: return "OnIntersectionEnterTrigger";
  39298. case 12: return "OnIntersectionExitTrigger";
  39299. case 13: return "OnKeyDownTrigger";
  39300. case 14: return "OnKeyUpTrigger";
  39301. case 15: return "OnPickOutTrigger";
  39302. default: return "";
  39303. }
  39304. };
  39305. return ActionManager;
  39306. }());
  39307. // Statics
  39308. ActionManager._NothingTrigger = 0;
  39309. ActionManager._OnPickTrigger = 1;
  39310. ActionManager._OnLeftPickTrigger = 2;
  39311. ActionManager._OnRightPickTrigger = 3;
  39312. ActionManager._OnCenterPickTrigger = 4;
  39313. ActionManager._OnPickDownTrigger = 5;
  39314. ActionManager._OnDoublePickTrigger = 6;
  39315. ActionManager._OnPickUpTrigger = 7;
  39316. ActionManager._OnLongPressTrigger = 8;
  39317. ActionManager._OnPointerOverTrigger = 9;
  39318. ActionManager._OnPointerOutTrigger = 10;
  39319. ActionManager._OnEveryFrameTrigger = 11;
  39320. ActionManager._OnIntersectionEnterTrigger = 12;
  39321. ActionManager._OnIntersectionExitTrigger = 13;
  39322. ActionManager._OnKeyDownTrigger = 14;
  39323. ActionManager._OnKeyUpTrigger = 15;
  39324. ActionManager._OnPickOutTrigger = 16;
  39325. ActionManager.Triggers = {};
  39326. BABYLON.ActionManager = ActionManager;
  39327. })(BABYLON || (BABYLON = {}));
  39328. //# sourceMappingURL=babylon.actionManager.js.map
  39329. var BABYLON;
  39330. (function (BABYLON) {
  39331. var InterpolateValueAction = (function (_super) {
  39332. __extends(InterpolateValueAction, _super);
  39333. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  39334. if (duration === void 0) { duration = 1000; }
  39335. var _this = _super.call(this, triggerOptions, condition) || this;
  39336. _this.propertyPath = propertyPath;
  39337. _this.value = value;
  39338. _this.duration = duration;
  39339. _this.stopOtherAnimations = stopOtherAnimations;
  39340. _this.onInterpolationDone = onInterpolationDone;
  39341. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  39342. _this._target = _this._effectiveTarget = target;
  39343. return _this;
  39344. }
  39345. InterpolateValueAction.prototype._prepare = function () {
  39346. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39347. this._property = this._getProperty(this.propertyPath);
  39348. };
  39349. InterpolateValueAction.prototype.execute = function () {
  39350. var _this = this;
  39351. var scene = this._actionManager.getScene();
  39352. var keys = [
  39353. {
  39354. frame: 0,
  39355. value: this._effectiveTarget[this._property]
  39356. }, {
  39357. frame: 100,
  39358. value: this.value
  39359. }
  39360. ];
  39361. var dataType;
  39362. if (typeof this.value === "number") {
  39363. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  39364. }
  39365. else if (this.value instanceof BABYLON.Color3) {
  39366. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  39367. }
  39368. else if (this.value instanceof BABYLON.Vector3) {
  39369. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  39370. }
  39371. else if (this.value instanceof BABYLON.Matrix) {
  39372. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  39373. }
  39374. else if (this.value instanceof BABYLON.Quaternion) {
  39375. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  39376. }
  39377. else {
  39378. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  39379. return;
  39380. }
  39381. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  39382. animation.setKeys(keys);
  39383. if (this.stopOtherAnimations) {
  39384. scene.stopAnimation(this._effectiveTarget);
  39385. }
  39386. var wrapper = function () {
  39387. _this.onInterpolationDoneObservable.notifyObservers(_this);
  39388. if (_this.onInterpolationDone) {
  39389. _this.onInterpolationDone();
  39390. }
  39391. };
  39392. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  39393. };
  39394. InterpolateValueAction.prototype.serialize = function (parent) {
  39395. return _super.prototype._serialize.call(this, {
  39396. name: "InterpolateValueAction",
  39397. properties: [
  39398. BABYLON.Action._GetTargetProperty(this._target),
  39399. { name: "propertyPath", value: this.propertyPath },
  39400. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39401. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  39402. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  39403. ]
  39404. }, parent);
  39405. };
  39406. return InterpolateValueAction;
  39407. }(BABYLON.Action));
  39408. BABYLON.InterpolateValueAction = InterpolateValueAction;
  39409. })(BABYLON || (BABYLON = {}));
  39410. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  39411. var BABYLON;
  39412. (function (BABYLON) {
  39413. var SwitchBooleanAction = (function (_super) {
  39414. __extends(SwitchBooleanAction, _super);
  39415. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  39416. var _this = _super.call(this, triggerOptions, condition) || this;
  39417. _this.propertyPath = propertyPath;
  39418. _this._target = _this._effectiveTarget = target;
  39419. return _this;
  39420. }
  39421. SwitchBooleanAction.prototype._prepare = function () {
  39422. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39423. this._property = this._getProperty(this.propertyPath);
  39424. };
  39425. SwitchBooleanAction.prototype.execute = function () {
  39426. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  39427. };
  39428. SwitchBooleanAction.prototype.serialize = function (parent) {
  39429. return _super.prototype._serialize.call(this, {
  39430. name: "SwitchBooleanAction",
  39431. properties: [
  39432. BABYLON.Action._GetTargetProperty(this._target),
  39433. { name: "propertyPath", value: this.propertyPath }
  39434. ]
  39435. }, parent);
  39436. };
  39437. return SwitchBooleanAction;
  39438. }(BABYLON.Action));
  39439. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  39440. var SetStateAction = (function (_super) {
  39441. __extends(SetStateAction, _super);
  39442. function SetStateAction(triggerOptions, target, value, condition) {
  39443. var _this = _super.call(this, triggerOptions, condition) || this;
  39444. _this.value = value;
  39445. _this._target = target;
  39446. return _this;
  39447. }
  39448. SetStateAction.prototype.execute = function () {
  39449. this._target.state = this.value;
  39450. };
  39451. SetStateAction.prototype.serialize = function (parent) {
  39452. return _super.prototype._serialize.call(this, {
  39453. name: "SetStateAction",
  39454. properties: [
  39455. BABYLON.Action._GetTargetProperty(this._target),
  39456. { name: "value", value: this.value }
  39457. ]
  39458. }, parent);
  39459. };
  39460. return SetStateAction;
  39461. }(BABYLON.Action));
  39462. BABYLON.SetStateAction = SetStateAction;
  39463. var SetValueAction = (function (_super) {
  39464. __extends(SetValueAction, _super);
  39465. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  39466. var _this = _super.call(this, triggerOptions, condition) || this;
  39467. _this.propertyPath = propertyPath;
  39468. _this.value = value;
  39469. _this._target = _this._effectiveTarget = target;
  39470. return _this;
  39471. }
  39472. SetValueAction.prototype._prepare = function () {
  39473. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39474. this._property = this._getProperty(this.propertyPath);
  39475. };
  39476. SetValueAction.prototype.execute = function () {
  39477. this._effectiveTarget[this._property] = this.value;
  39478. if (this._target.markAsDirty) {
  39479. this._target.markAsDirty(this._property);
  39480. }
  39481. };
  39482. SetValueAction.prototype.serialize = function (parent) {
  39483. return _super.prototype._serialize.call(this, {
  39484. name: "SetValueAction",
  39485. properties: [
  39486. BABYLON.Action._GetTargetProperty(this._target),
  39487. { name: "propertyPath", value: this.propertyPath },
  39488. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39489. ]
  39490. }, parent);
  39491. };
  39492. return SetValueAction;
  39493. }(BABYLON.Action));
  39494. BABYLON.SetValueAction = SetValueAction;
  39495. var IncrementValueAction = (function (_super) {
  39496. __extends(IncrementValueAction, _super);
  39497. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  39498. var _this = _super.call(this, triggerOptions, condition) || this;
  39499. _this.propertyPath = propertyPath;
  39500. _this.value = value;
  39501. _this._target = _this._effectiveTarget = target;
  39502. return _this;
  39503. }
  39504. IncrementValueAction.prototype._prepare = function () {
  39505. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39506. this._property = this._getProperty(this.propertyPath);
  39507. if (typeof this._effectiveTarget[this._property] !== "number") {
  39508. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  39509. }
  39510. };
  39511. IncrementValueAction.prototype.execute = function () {
  39512. this._effectiveTarget[this._property] += this.value;
  39513. if (this._target.markAsDirty) {
  39514. this._target.markAsDirty(this._property);
  39515. }
  39516. };
  39517. IncrementValueAction.prototype.serialize = function (parent) {
  39518. return _super.prototype._serialize.call(this, {
  39519. name: "IncrementValueAction",
  39520. properties: [
  39521. BABYLON.Action._GetTargetProperty(this._target),
  39522. { name: "propertyPath", value: this.propertyPath },
  39523. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39524. ]
  39525. }, parent);
  39526. };
  39527. return IncrementValueAction;
  39528. }(BABYLON.Action));
  39529. BABYLON.IncrementValueAction = IncrementValueAction;
  39530. var PlayAnimationAction = (function (_super) {
  39531. __extends(PlayAnimationAction, _super);
  39532. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  39533. var _this = _super.call(this, triggerOptions, condition) || this;
  39534. _this.from = from;
  39535. _this.to = to;
  39536. _this.loop = loop;
  39537. _this._target = target;
  39538. return _this;
  39539. }
  39540. PlayAnimationAction.prototype._prepare = function () {
  39541. };
  39542. PlayAnimationAction.prototype.execute = function () {
  39543. var scene = this._actionManager.getScene();
  39544. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  39545. };
  39546. PlayAnimationAction.prototype.serialize = function (parent) {
  39547. return _super.prototype._serialize.call(this, {
  39548. name: "PlayAnimationAction",
  39549. properties: [
  39550. BABYLON.Action._GetTargetProperty(this._target),
  39551. { name: "from", value: String(this.from) },
  39552. { name: "to", value: String(this.to) },
  39553. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  39554. ]
  39555. }, parent);
  39556. };
  39557. return PlayAnimationAction;
  39558. }(BABYLON.Action));
  39559. BABYLON.PlayAnimationAction = PlayAnimationAction;
  39560. var StopAnimationAction = (function (_super) {
  39561. __extends(StopAnimationAction, _super);
  39562. function StopAnimationAction(triggerOptions, target, condition) {
  39563. var _this = _super.call(this, triggerOptions, condition) || this;
  39564. _this._target = target;
  39565. return _this;
  39566. }
  39567. StopAnimationAction.prototype._prepare = function () {
  39568. };
  39569. StopAnimationAction.prototype.execute = function () {
  39570. var scene = this._actionManager.getScene();
  39571. scene.stopAnimation(this._target);
  39572. };
  39573. StopAnimationAction.prototype.serialize = function (parent) {
  39574. return _super.prototype._serialize.call(this, {
  39575. name: "StopAnimationAction",
  39576. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  39577. }, parent);
  39578. };
  39579. return StopAnimationAction;
  39580. }(BABYLON.Action));
  39581. BABYLON.StopAnimationAction = StopAnimationAction;
  39582. var DoNothingAction = (function (_super) {
  39583. __extends(DoNothingAction, _super);
  39584. function DoNothingAction(triggerOptions, condition) {
  39585. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  39586. return _super.call(this, triggerOptions, condition) || this;
  39587. }
  39588. DoNothingAction.prototype.execute = function () {
  39589. };
  39590. DoNothingAction.prototype.serialize = function (parent) {
  39591. return _super.prototype._serialize.call(this, {
  39592. name: "DoNothingAction",
  39593. properties: []
  39594. }, parent);
  39595. };
  39596. return DoNothingAction;
  39597. }(BABYLON.Action));
  39598. BABYLON.DoNothingAction = DoNothingAction;
  39599. var CombineAction = (function (_super) {
  39600. __extends(CombineAction, _super);
  39601. function CombineAction(triggerOptions, children, condition) {
  39602. var _this = _super.call(this, triggerOptions, condition) || this;
  39603. _this.children = children;
  39604. return _this;
  39605. }
  39606. CombineAction.prototype._prepare = function () {
  39607. for (var index = 0; index < this.children.length; index++) {
  39608. this.children[index]._actionManager = this._actionManager;
  39609. this.children[index]._prepare();
  39610. }
  39611. };
  39612. CombineAction.prototype.execute = function (evt) {
  39613. for (var index = 0; index < this.children.length; index++) {
  39614. this.children[index].execute(evt);
  39615. }
  39616. };
  39617. CombineAction.prototype.serialize = function (parent) {
  39618. var serializationObject = _super.prototype._serialize.call(this, {
  39619. name: "CombineAction",
  39620. properties: [],
  39621. combine: []
  39622. }, parent);
  39623. for (var i = 0; i < this.children.length; i++) {
  39624. serializationObject.combine.push(this.children[i].serialize(null));
  39625. }
  39626. return serializationObject;
  39627. };
  39628. return CombineAction;
  39629. }(BABYLON.Action));
  39630. BABYLON.CombineAction = CombineAction;
  39631. var ExecuteCodeAction = (function (_super) {
  39632. __extends(ExecuteCodeAction, _super);
  39633. function ExecuteCodeAction(triggerOptions, func, condition) {
  39634. var _this = _super.call(this, triggerOptions, condition) || this;
  39635. _this.func = func;
  39636. return _this;
  39637. }
  39638. ExecuteCodeAction.prototype.execute = function (evt) {
  39639. this.func(evt);
  39640. };
  39641. return ExecuteCodeAction;
  39642. }(BABYLON.Action));
  39643. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  39644. var SetParentAction = (function (_super) {
  39645. __extends(SetParentAction, _super);
  39646. function SetParentAction(triggerOptions, target, parent, condition) {
  39647. var _this = _super.call(this, triggerOptions, condition) || this;
  39648. _this._target = target;
  39649. _this._parent = parent;
  39650. return _this;
  39651. }
  39652. SetParentAction.prototype._prepare = function () {
  39653. };
  39654. SetParentAction.prototype.execute = function () {
  39655. if (this._target.parent === this._parent) {
  39656. return;
  39657. }
  39658. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  39659. invertParentWorldMatrix.invert();
  39660. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  39661. this._target.parent = this._parent;
  39662. };
  39663. SetParentAction.prototype.serialize = function (parent) {
  39664. return _super.prototype._serialize.call(this, {
  39665. name: "SetParentAction",
  39666. properties: [
  39667. BABYLON.Action._GetTargetProperty(this._target),
  39668. BABYLON.Action._GetTargetProperty(this._parent),
  39669. ]
  39670. }, parent);
  39671. };
  39672. return SetParentAction;
  39673. }(BABYLON.Action));
  39674. BABYLON.SetParentAction = SetParentAction;
  39675. var PlaySoundAction = (function (_super) {
  39676. __extends(PlaySoundAction, _super);
  39677. function PlaySoundAction(triggerOptions, sound, condition) {
  39678. var _this = _super.call(this, triggerOptions, condition) || this;
  39679. _this._sound = sound;
  39680. return _this;
  39681. }
  39682. PlaySoundAction.prototype._prepare = function () {
  39683. };
  39684. PlaySoundAction.prototype.execute = function () {
  39685. if (this._sound !== undefined)
  39686. this._sound.play();
  39687. };
  39688. PlaySoundAction.prototype.serialize = function (parent) {
  39689. return _super.prototype._serialize.call(this, {
  39690. name: "PlaySoundAction",
  39691. properties: [{ name: "sound", value: this._sound.name }]
  39692. }, parent);
  39693. };
  39694. return PlaySoundAction;
  39695. }(BABYLON.Action));
  39696. BABYLON.PlaySoundAction = PlaySoundAction;
  39697. var StopSoundAction = (function (_super) {
  39698. __extends(StopSoundAction, _super);
  39699. function StopSoundAction(triggerOptions, sound, condition) {
  39700. var _this = _super.call(this, triggerOptions, condition) || this;
  39701. _this._sound = sound;
  39702. return _this;
  39703. }
  39704. StopSoundAction.prototype._prepare = function () {
  39705. };
  39706. StopSoundAction.prototype.execute = function () {
  39707. if (this._sound !== undefined)
  39708. this._sound.stop();
  39709. };
  39710. StopSoundAction.prototype.serialize = function (parent) {
  39711. return _super.prototype._serialize.call(this, {
  39712. name: "StopSoundAction",
  39713. properties: [{ name: "sound", value: this._sound.name }]
  39714. }, parent);
  39715. };
  39716. return StopSoundAction;
  39717. }(BABYLON.Action));
  39718. BABYLON.StopSoundAction = StopSoundAction;
  39719. })(BABYLON || (BABYLON = {}));
  39720. //# sourceMappingURL=babylon.directActions.js.map
  39721. var BABYLON;
  39722. (function (BABYLON) {
  39723. var SpriteManager = (function () {
  39724. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  39725. if (epsilon === void 0) { epsilon = 0.01; }
  39726. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39727. this.name = name;
  39728. this.sprites = new Array();
  39729. this.renderingGroupId = 0;
  39730. this.layerMask = 0x0FFFFFFF;
  39731. this.fogEnabled = true;
  39732. this.isPickable = false;
  39733. /**
  39734. * An event triggered when the manager is disposed.
  39735. * @type {BABYLON.Observable}
  39736. */
  39737. this.onDisposeObservable = new BABYLON.Observable();
  39738. this._vertexBuffers = {};
  39739. this._capacity = capacity;
  39740. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  39741. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39742. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39743. if (cellSize.width && cellSize.height) {
  39744. this.cellWidth = cellSize.width;
  39745. this.cellHeight = cellSize.height;
  39746. }
  39747. else if (cellSize !== undefined) {
  39748. this.cellWidth = cellSize;
  39749. this.cellHeight = cellSize;
  39750. }
  39751. else {
  39752. return;
  39753. }
  39754. this._epsilon = epsilon;
  39755. this._scene = scene;
  39756. this._scene.spriteManagers.push(this);
  39757. var indices = [];
  39758. var index = 0;
  39759. for (var count = 0; count < capacity; count++) {
  39760. indices.push(index);
  39761. indices.push(index + 1);
  39762. indices.push(index + 2);
  39763. indices.push(index);
  39764. indices.push(index + 2);
  39765. indices.push(index + 3);
  39766. index += 4;
  39767. }
  39768. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  39769. // VBO
  39770. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  39771. this._vertexData = new Float32Array(capacity * 16 * 4);
  39772. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  39773. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  39774. var options = this._buffer.createVertexBuffer("options", 4, 4);
  39775. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  39776. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  39777. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  39778. this._vertexBuffers["options"] = options;
  39779. this._vertexBuffers["cellInfo"] = cellInfo;
  39780. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  39781. // Effects
  39782. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  39783. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  39784. }
  39785. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  39786. set: function (callback) {
  39787. if (this._onDisposeObserver) {
  39788. this.onDisposeObservable.remove(this._onDisposeObserver);
  39789. }
  39790. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  39791. },
  39792. enumerable: true,
  39793. configurable: true
  39794. });
  39795. Object.defineProperty(SpriteManager.prototype, "texture", {
  39796. get: function () {
  39797. return this._spriteTexture;
  39798. },
  39799. set: function (value) {
  39800. this._spriteTexture = value;
  39801. },
  39802. enumerable: true,
  39803. configurable: true
  39804. });
  39805. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  39806. var arrayOffset = index * 16;
  39807. if (offsetX === 0)
  39808. offsetX = this._epsilon;
  39809. else if (offsetX === 1)
  39810. offsetX = 1 - this._epsilon;
  39811. if (offsetY === 0)
  39812. offsetY = this._epsilon;
  39813. else if (offsetY === 1)
  39814. offsetY = 1 - this._epsilon;
  39815. this._vertexData[arrayOffset] = sprite.position.x;
  39816. this._vertexData[arrayOffset + 1] = sprite.position.y;
  39817. this._vertexData[arrayOffset + 2] = sprite.position.z;
  39818. this._vertexData[arrayOffset + 3] = sprite.angle;
  39819. this._vertexData[arrayOffset + 4] = sprite.width;
  39820. this._vertexData[arrayOffset + 5] = sprite.height;
  39821. this._vertexData[arrayOffset + 6] = offsetX;
  39822. this._vertexData[arrayOffset + 7] = offsetY;
  39823. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  39824. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  39825. var offset = (sprite.cellIndex / rowSize) >> 0;
  39826. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  39827. this._vertexData[arrayOffset + 11] = offset;
  39828. // Color
  39829. this._vertexData[arrayOffset + 12] = sprite.color.r;
  39830. this._vertexData[arrayOffset + 13] = sprite.color.g;
  39831. this._vertexData[arrayOffset + 14] = sprite.color.b;
  39832. this._vertexData[arrayOffset + 15] = sprite.color.a;
  39833. };
  39834. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  39835. var count = Math.min(this._capacity, this.sprites.length);
  39836. var min = BABYLON.Vector3.Zero();
  39837. var max = BABYLON.Vector3.Zero();
  39838. var distance = Number.MAX_VALUE;
  39839. var currentSprite;
  39840. var cameraSpacePosition = BABYLON.Vector3.Zero();
  39841. var cameraView = camera.getViewMatrix();
  39842. for (var index = 0; index < count; index++) {
  39843. var sprite = this.sprites[index];
  39844. if (!sprite) {
  39845. continue;
  39846. }
  39847. if (predicate) {
  39848. if (!predicate(sprite)) {
  39849. continue;
  39850. }
  39851. }
  39852. else if (!sprite.isPickable) {
  39853. continue;
  39854. }
  39855. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  39856. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  39857. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  39858. if (ray.intersectsBoxMinMax(min, max)) {
  39859. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  39860. if (distance > currentDistance) {
  39861. distance = currentDistance;
  39862. currentSprite = sprite;
  39863. if (fastCheck) {
  39864. break;
  39865. }
  39866. }
  39867. }
  39868. }
  39869. if (currentSprite) {
  39870. var result = new BABYLON.PickingInfo();
  39871. result.hit = true;
  39872. result.pickedSprite = currentSprite;
  39873. result.distance = distance;
  39874. return result;
  39875. }
  39876. return null;
  39877. };
  39878. SpriteManager.prototype.render = function () {
  39879. // Check
  39880. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  39881. return;
  39882. var engine = this._scene.getEngine();
  39883. var baseSize = this._spriteTexture.getBaseSize();
  39884. // Sprites
  39885. var deltaTime = engine.getDeltaTime();
  39886. var max = Math.min(this._capacity, this.sprites.length);
  39887. var rowSize = baseSize.width / this.cellWidth;
  39888. var offset = 0;
  39889. for (var index = 0; index < max; index++) {
  39890. var sprite = this.sprites[index];
  39891. if (!sprite) {
  39892. continue;
  39893. }
  39894. sprite._animate(deltaTime);
  39895. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  39896. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  39897. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  39898. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  39899. }
  39900. this._buffer.update(this._vertexData);
  39901. // Render
  39902. var effect = this._effectBase;
  39903. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39904. effect = this._effectFog;
  39905. }
  39906. engine.enableEffect(effect);
  39907. var viewMatrix = this._scene.getViewMatrix();
  39908. effect.setTexture("diffuseSampler", this._spriteTexture);
  39909. effect.setMatrix("view", viewMatrix);
  39910. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  39911. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  39912. // Fog
  39913. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39914. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  39915. effect.setColor3("vFogColor", this._scene.fogColor);
  39916. }
  39917. // VBOs
  39918. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39919. // Draw order
  39920. engine.setDepthFunctionToLessOrEqual();
  39921. effect.setBool("alphaTest", true);
  39922. engine.setColorWrite(false);
  39923. engine.draw(true, 0, max * 6);
  39924. engine.setColorWrite(true);
  39925. effect.setBool("alphaTest", false);
  39926. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39927. engine.draw(true, 0, max * 6);
  39928. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39929. };
  39930. SpriteManager.prototype.dispose = function () {
  39931. if (this._buffer) {
  39932. this._buffer.dispose();
  39933. this._buffer = null;
  39934. }
  39935. if (this._indexBuffer) {
  39936. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39937. this._indexBuffer = null;
  39938. }
  39939. if (this._spriteTexture) {
  39940. this._spriteTexture.dispose();
  39941. this._spriteTexture = null;
  39942. }
  39943. // Remove from scene
  39944. var index = this._scene.spriteManagers.indexOf(this);
  39945. this._scene.spriteManagers.splice(index, 1);
  39946. // Callback
  39947. this.onDisposeObservable.notifyObservers(this);
  39948. this.onDisposeObservable.clear();
  39949. };
  39950. return SpriteManager;
  39951. }());
  39952. BABYLON.SpriteManager = SpriteManager;
  39953. })(BABYLON || (BABYLON = {}));
  39954. //# sourceMappingURL=babylon.spriteManager.js.map
  39955. var BABYLON;
  39956. (function (BABYLON) {
  39957. var Sprite = (function () {
  39958. function Sprite(name, manager) {
  39959. this.name = name;
  39960. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39961. this.width = 1.0;
  39962. this.height = 1.0;
  39963. this.angle = 0;
  39964. this.cellIndex = 0;
  39965. this.invertU = 0;
  39966. this.invertV = 0;
  39967. this.animations = new Array();
  39968. this.isPickable = false;
  39969. this._animationStarted = false;
  39970. this._loopAnimation = false;
  39971. this._fromIndex = 0;
  39972. this._toIndex = 0;
  39973. this._delay = 0;
  39974. this._direction = 1;
  39975. this._frameCount = 0;
  39976. this._time = 0;
  39977. this._manager = manager;
  39978. this._manager.sprites.push(this);
  39979. this.position = BABYLON.Vector3.Zero();
  39980. }
  39981. Object.defineProperty(Sprite.prototype, "size", {
  39982. get: function () {
  39983. return this.width;
  39984. },
  39985. set: function (value) {
  39986. this.width = value;
  39987. this.height = value;
  39988. },
  39989. enumerable: true,
  39990. configurable: true
  39991. });
  39992. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  39993. this._fromIndex = from;
  39994. this._toIndex = to;
  39995. this._loopAnimation = loop;
  39996. this._delay = delay;
  39997. this._animationStarted = true;
  39998. this._direction = from < to ? 1 : -1;
  39999. this.cellIndex = from;
  40000. this._time = 0;
  40001. this._onAnimationEnd = onAnimationEnd;
  40002. };
  40003. Sprite.prototype.stopAnimation = function () {
  40004. this._animationStarted = false;
  40005. };
  40006. Sprite.prototype._animate = function (deltaTime) {
  40007. if (!this._animationStarted)
  40008. return;
  40009. this._time += deltaTime;
  40010. if (this._time > this._delay) {
  40011. this._time = this._time % this._delay;
  40012. this.cellIndex += this._direction;
  40013. if (this.cellIndex > this._toIndex) {
  40014. if (this._loopAnimation) {
  40015. this.cellIndex = this._fromIndex;
  40016. }
  40017. else {
  40018. this.cellIndex = this._toIndex;
  40019. this._animationStarted = false;
  40020. if (this._onAnimationEnd) {
  40021. this._onAnimationEnd();
  40022. }
  40023. if (this.disposeWhenFinishedAnimating) {
  40024. this.dispose();
  40025. }
  40026. }
  40027. }
  40028. }
  40029. };
  40030. Sprite.prototype.dispose = function () {
  40031. for (var i = 0; i < this._manager.sprites.length; i++) {
  40032. if (this._manager.sprites[i] == this) {
  40033. this._manager.sprites.splice(i, 1);
  40034. }
  40035. }
  40036. };
  40037. return Sprite;
  40038. }());
  40039. BABYLON.Sprite = Sprite;
  40040. })(BABYLON || (BABYLON = {}));
  40041. //# sourceMappingURL=babylon.sprite.js.map
  40042. var BABYLON;
  40043. (function (BABYLON) {
  40044. var IntersectionInfo = (function () {
  40045. function IntersectionInfo(bu, bv, distance) {
  40046. this.bu = bu;
  40047. this.bv = bv;
  40048. this.distance = distance;
  40049. this.faceId = 0;
  40050. this.subMeshId = 0;
  40051. }
  40052. return IntersectionInfo;
  40053. }());
  40054. BABYLON.IntersectionInfo = IntersectionInfo;
  40055. var PickingInfo = (function () {
  40056. function PickingInfo() {
  40057. this.hit = false;
  40058. this.distance = 0;
  40059. this.pickedPoint = null;
  40060. this.pickedMesh = null;
  40061. this.bu = 0;
  40062. this.bv = 0;
  40063. this.faceId = -1;
  40064. this.subMeshId = 0;
  40065. this.pickedSprite = null;
  40066. }
  40067. // Methods
  40068. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  40069. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  40070. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  40071. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40072. return null;
  40073. }
  40074. var indices = this.pickedMesh.getIndices();
  40075. var result;
  40076. if (useVerticesNormals) {
  40077. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40078. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  40079. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  40080. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  40081. normal0 = normal0.scale(this.bu);
  40082. normal1 = normal1.scale(this.bv);
  40083. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  40084. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  40085. }
  40086. else {
  40087. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40088. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  40089. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  40090. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  40091. var p1p2 = vertex1.subtract(vertex2);
  40092. var p3p2 = vertex3.subtract(vertex2);
  40093. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  40094. }
  40095. if (useWorldCoordinates) {
  40096. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  40097. }
  40098. return BABYLON.Vector3.Normalize(result);
  40099. };
  40100. PickingInfo.prototype.getTextureCoordinates = function () {
  40101. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40102. return null;
  40103. }
  40104. var indices = this.pickedMesh.getIndices();
  40105. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40106. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  40107. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  40108. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  40109. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  40110. uv1 = uv1.scale(this.bu);
  40111. uv2 = uv2.scale(this.bv);
  40112. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  40113. };
  40114. return PickingInfo;
  40115. }());
  40116. BABYLON.PickingInfo = PickingInfo;
  40117. })(BABYLON || (BABYLON = {}));
  40118. //# sourceMappingURL=babylon.pickingInfo.js.map
  40119. var BABYLON;
  40120. (function (BABYLON) {
  40121. var Ray = (function () {
  40122. function Ray(origin, direction, length) {
  40123. if (length === void 0) { length = Number.MAX_VALUE; }
  40124. this.origin = origin;
  40125. this.direction = direction;
  40126. this.length = length;
  40127. }
  40128. // Methods
  40129. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  40130. var d = 0.0;
  40131. var maxValue = Number.MAX_VALUE;
  40132. var inv;
  40133. var min;
  40134. var max;
  40135. var temp;
  40136. if (Math.abs(this.direction.x) < 0.0000001) {
  40137. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  40138. return false;
  40139. }
  40140. }
  40141. else {
  40142. inv = 1.0 / this.direction.x;
  40143. min = (minimum.x - this.origin.x) * inv;
  40144. max = (maximum.x - this.origin.x) * inv;
  40145. if (max === -Infinity) {
  40146. max = Infinity;
  40147. }
  40148. if (min > max) {
  40149. temp = min;
  40150. min = max;
  40151. max = temp;
  40152. }
  40153. d = Math.max(min, d);
  40154. maxValue = Math.min(max, maxValue);
  40155. if (d > maxValue) {
  40156. return false;
  40157. }
  40158. }
  40159. if (Math.abs(this.direction.y) < 0.0000001) {
  40160. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  40161. return false;
  40162. }
  40163. }
  40164. else {
  40165. inv = 1.0 / this.direction.y;
  40166. min = (minimum.y - this.origin.y) * inv;
  40167. max = (maximum.y - this.origin.y) * inv;
  40168. if (max === -Infinity) {
  40169. max = Infinity;
  40170. }
  40171. if (min > max) {
  40172. temp = min;
  40173. min = max;
  40174. max = temp;
  40175. }
  40176. d = Math.max(min, d);
  40177. maxValue = Math.min(max, maxValue);
  40178. if (d > maxValue) {
  40179. return false;
  40180. }
  40181. }
  40182. if (Math.abs(this.direction.z) < 0.0000001) {
  40183. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  40184. return false;
  40185. }
  40186. }
  40187. else {
  40188. inv = 1.0 / this.direction.z;
  40189. min = (minimum.z - this.origin.z) * inv;
  40190. max = (maximum.z - this.origin.z) * inv;
  40191. if (max === -Infinity) {
  40192. max = Infinity;
  40193. }
  40194. if (min > max) {
  40195. temp = min;
  40196. min = max;
  40197. max = temp;
  40198. }
  40199. d = Math.max(min, d);
  40200. maxValue = Math.min(max, maxValue);
  40201. if (d > maxValue) {
  40202. return false;
  40203. }
  40204. }
  40205. return true;
  40206. };
  40207. Ray.prototype.intersectsBox = function (box) {
  40208. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  40209. };
  40210. Ray.prototype.intersectsSphere = function (sphere) {
  40211. var x = sphere.center.x - this.origin.x;
  40212. var y = sphere.center.y - this.origin.y;
  40213. var z = sphere.center.z - this.origin.z;
  40214. var pyth = (x * x) + (y * y) + (z * z);
  40215. var rr = sphere.radius * sphere.radius;
  40216. if (pyth <= rr) {
  40217. return true;
  40218. }
  40219. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  40220. if (dot < 0.0) {
  40221. return false;
  40222. }
  40223. var temp = pyth - (dot * dot);
  40224. return temp <= rr;
  40225. };
  40226. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  40227. if (!this._edge1) {
  40228. this._edge1 = BABYLON.Vector3.Zero();
  40229. this._edge2 = BABYLON.Vector3.Zero();
  40230. this._pvec = BABYLON.Vector3.Zero();
  40231. this._tvec = BABYLON.Vector3.Zero();
  40232. this._qvec = BABYLON.Vector3.Zero();
  40233. }
  40234. vertex1.subtractToRef(vertex0, this._edge1);
  40235. vertex2.subtractToRef(vertex0, this._edge2);
  40236. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  40237. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  40238. if (det === 0) {
  40239. return null;
  40240. }
  40241. var invdet = 1 / det;
  40242. this.origin.subtractToRef(vertex0, this._tvec);
  40243. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  40244. if (bu < 0 || bu > 1.0) {
  40245. return null;
  40246. }
  40247. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  40248. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  40249. if (bv < 0 || bu + bv > 1.0) {
  40250. return null;
  40251. }
  40252. //check if the distance is longer than the predefined length.
  40253. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  40254. if (distance > this.length) {
  40255. return null;
  40256. }
  40257. return new BABYLON.IntersectionInfo(bu, bv, distance);
  40258. };
  40259. Ray.prototype.intersectsPlane = function (plane) {
  40260. var distance;
  40261. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  40262. if (Math.abs(result1) < 9.99999997475243E-07) {
  40263. return null;
  40264. }
  40265. else {
  40266. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  40267. distance = (-plane.d - result2) / result1;
  40268. if (distance < 0.0) {
  40269. if (distance < -9.99999997475243E-07) {
  40270. return null;
  40271. }
  40272. else {
  40273. return 0;
  40274. }
  40275. }
  40276. return distance;
  40277. }
  40278. };
  40279. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  40280. var tm = BABYLON.Tmp.Matrix[0];
  40281. mesh.getWorldMatrix().invertToRef(tm);
  40282. if (this._tmpRay) {
  40283. Ray.TransformToRef(this, tm, this._tmpRay);
  40284. }
  40285. else {
  40286. this._tmpRay = Ray.Transform(this, tm);
  40287. }
  40288. return mesh.intersects(this._tmpRay, fastCheck);
  40289. };
  40290. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  40291. if (results) {
  40292. results.length = 0;
  40293. }
  40294. else {
  40295. results = [];
  40296. }
  40297. for (var i = 0; i < meshes.length; i++) {
  40298. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  40299. if (pickInfo.hit) {
  40300. results.push(pickInfo);
  40301. }
  40302. }
  40303. results.sort(this._comparePickingInfo);
  40304. return results;
  40305. };
  40306. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  40307. if (pickingInfoA.distance < pickingInfoB.distance) {
  40308. return -1;
  40309. }
  40310. else if (pickingInfoA.distance > pickingInfoB.distance) {
  40311. return 1;
  40312. }
  40313. else {
  40314. return 0;
  40315. }
  40316. };
  40317. /**
  40318. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  40319. * @param sega the first point of the segment to test the intersection against
  40320. * @param segb the second point of the segment to test the intersection against
  40321. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  40322. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  40323. */
  40324. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  40325. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  40326. var u = segb.subtract(sega);
  40327. var v = rsegb.subtract(this.origin);
  40328. var w = sega.subtract(this.origin);
  40329. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  40330. var b = BABYLON.Vector3.Dot(u, v);
  40331. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  40332. var d = BABYLON.Vector3.Dot(u, w);
  40333. var e = BABYLON.Vector3.Dot(v, w);
  40334. var D = a * c - b * b; // always >= 0
  40335. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  40336. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  40337. // compute the line parameters of the two closest points
  40338. if (D < Ray.smallnum) {
  40339. sN = 0.0; // force using point P0 on segment S1
  40340. sD = 1.0; // to prevent possible division by 0.0 later
  40341. tN = e;
  40342. tD = c;
  40343. }
  40344. else {
  40345. sN = (b * e - c * d);
  40346. tN = (a * e - b * d);
  40347. if (sN < 0.0) {
  40348. sN = 0.0;
  40349. tN = e;
  40350. tD = c;
  40351. }
  40352. else if (sN > sD) {
  40353. sN = sD;
  40354. tN = e + b;
  40355. tD = c;
  40356. }
  40357. }
  40358. if (tN < 0.0) {
  40359. tN = 0.0;
  40360. // recompute sc for this edge
  40361. if (-d < 0.0) {
  40362. sN = 0.0;
  40363. }
  40364. else if (-d > a)
  40365. sN = sD;
  40366. else {
  40367. sN = -d;
  40368. sD = a;
  40369. }
  40370. }
  40371. else if (tN > tD) {
  40372. tN = tD;
  40373. // recompute sc for this edge
  40374. if ((-d + b) < 0.0) {
  40375. sN = 0;
  40376. }
  40377. else if ((-d + b) > a) {
  40378. sN = sD;
  40379. }
  40380. else {
  40381. sN = (-d + b);
  40382. sD = a;
  40383. }
  40384. }
  40385. // finally do the division to get sc and tc
  40386. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  40387. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  40388. // get the difference of the two closest points
  40389. var qtc = v.multiplyByFloats(tc, tc, tc);
  40390. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  40391. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  40392. if (isIntersected) {
  40393. return qtc.length();
  40394. }
  40395. return -1;
  40396. };
  40397. // Statics
  40398. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  40399. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  40400. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  40401. var direction = end.subtract(start);
  40402. direction.normalize();
  40403. return new Ray(start, direction);
  40404. };
  40405. /**
  40406. * 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
  40407. * transformed to the given world matrix.
  40408. * @param origin The origin point
  40409. * @param end The end point
  40410. * @param world a matrix to transform the ray to. Default is the identity matrix.
  40411. */
  40412. Ray.CreateNewFromTo = function (origin, end, world) {
  40413. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  40414. var direction = end.subtract(origin);
  40415. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  40416. direction.normalize();
  40417. return Ray.Transform(new Ray(origin, direction, length), world);
  40418. };
  40419. Ray.Transform = function (ray, matrix) {
  40420. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  40421. Ray.TransformToRef(ray, matrix, result);
  40422. return result;
  40423. };
  40424. Ray.TransformToRef = function (ray, matrix, result) {
  40425. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  40426. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  40427. result.length = ray.length;
  40428. var dir = result.direction;
  40429. var len = dir.length();
  40430. if (!(len === 0 || len === 1)) {
  40431. var num = 1.0 / len;
  40432. dir.x *= num;
  40433. dir.y *= num;
  40434. dir.z *= num;
  40435. result.length *= len;
  40436. }
  40437. };
  40438. return Ray;
  40439. }());
  40440. Ray.smallnum = 0.00000001;
  40441. Ray.rayl = 10e8;
  40442. BABYLON.Ray = Ray;
  40443. })(BABYLON || (BABYLON = {}));
  40444. //# sourceMappingURL=babylon.ray.js.map
  40445. var BABYLON;
  40446. (function (BABYLON) {
  40447. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  40448. if (boxMin.x > sphereCenter.x + sphereRadius)
  40449. return false;
  40450. if (sphereCenter.x - sphereRadius > boxMax.x)
  40451. return false;
  40452. if (boxMin.y > sphereCenter.y + sphereRadius)
  40453. return false;
  40454. if (sphereCenter.y - sphereRadius > boxMax.y)
  40455. return false;
  40456. if (boxMin.z > sphereCenter.z + sphereRadius)
  40457. return false;
  40458. if (sphereCenter.z - sphereRadius > boxMax.z)
  40459. return false;
  40460. return true;
  40461. };
  40462. var getLowestRoot = (function () {
  40463. var result = { root: 0, found: false };
  40464. return function (a, b, c, maxR) {
  40465. result.root = 0;
  40466. result.found = false;
  40467. var determinant = b * b - 4.0 * a * c;
  40468. if (determinant < 0)
  40469. return result;
  40470. var sqrtD = Math.sqrt(determinant);
  40471. var r1 = (-b - sqrtD) / (2.0 * a);
  40472. var r2 = (-b + sqrtD) / (2.0 * a);
  40473. if (r1 > r2) {
  40474. var temp = r2;
  40475. r2 = r1;
  40476. r1 = temp;
  40477. }
  40478. if (r1 > 0 && r1 < maxR) {
  40479. result.root = r1;
  40480. result.found = true;
  40481. return result;
  40482. }
  40483. if (r2 > 0 && r2 < maxR) {
  40484. result.root = r2;
  40485. result.found = true;
  40486. return result;
  40487. }
  40488. return result;
  40489. };
  40490. })();
  40491. var Collider = (function () {
  40492. function Collider() {
  40493. this.radius = BABYLON.Vector3.One();
  40494. this.retry = 0;
  40495. this.basePointWorld = BABYLON.Vector3.Zero();
  40496. this.velocityWorld = BABYLON.Vector3.Zero();
  40497. this.normalizedVelocity = BABYLON.Vector3.Zero();
  40498. this._collisionPoint = BABYLON.Vector3.Zero();
  40499. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  40500. this._tempVector = BABYLON.Vector3.Zero();
  40501. this._tempVector2 = BABYLON.Vector3.Zero();
  40502. this._tempVector3 = BABYLON.Vector3.Zero();
  40503. this._tempVector4 = BABYLON.Vector3.Zero();
  40504. this._edge = BABYLON.Vector3.Zero();
  40505. this._baseToVertex = BABYLON.Vector3.Zero();
  40506. this._destinationPoint = BABYLON.Vector3.Zero();
  40507. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  40508. this._displacementVector = BABYLON.Vector3.Zero();
  40509. this._collisionMask = -1;
  40510. }
  40511. Object.defineProperty(Collider.prototype, "collisionMask", {
  40512. get: function () {
  40513. return this._collisionMask;
  40514. },
  40515. set: function (mask) {
  40516. this._collisionMask = !isNaN(mask) ? mask : -1;
  40517. },
  40518. enumerable: true,
  40519. configurable: true
  40520. });
  40521. // Methods
  40522. Collider.prototype._initialize = function (source, dir, e) {
  40523. this.velocity = dir;
  40524. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  40525. this.basePoint = source;
  40526. source.multiplyToRef(this.radius, this.basePointWorld);
  40527. dir.multiplyToRef(this.radius, this.velocityWorld);
  40528. this.velocityWorldLength = this.velocityWorld.length();
  40529. this.epsilon = e;
  40530. this.collisionFound = false;
  40531. };
  40532. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  40533. pa.subtractToRef(point, this._tempVector);
  40534. pb.subtractToRef(point, this._tempVector2);
  40535. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  40536. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40537. if (d < 0)
  40538. return false;
  40539. pc.subtractToRef(point, this._tempVector3);
  40540. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  40541. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40542. if (d < 0)
  40543. return false;
  40544. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  40545. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40546. return d >= 0;
  40547. };
  40548. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  40549. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  40550. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  40551. if (distance > this.velocityWorldLength + max + sphereRadius) {
  40552. return false;
  40553. }
  40554. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  40555. return false;
  40556. return true;
  40557. };
  40558. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  40559. var t0;
  40560. var embeddedInPlane = false;
  40561. //defensive programming, actually not needed.
  40562. if (!trianglePlaneArray) {
  40563. trianglePlaneArray = [];
  40564. }
  40565. if (!trianglePlaneArray[faceIndex]) {
  40566. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  40567. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  40568. }
  40569. var trianglePlane = trianglePlaneArray[faceIndex];
  40570. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  40571. return;
  40572. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  40573. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  40574. if (normalDotVelocity == 0) {
  40575. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  40576. return;
  40577. embeddedInPlane = true;
  40578. t0 = 0;
  40579. }
  40580. else {
  40581. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  40582. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  40583. if (t0 > t1) {
  40584. var temp = t1;
  40585. t1 = t0;
  40586. t0 = temp;
  40587. }
  40588. if (t0 > 1.0 || t1 < 0.0)
  40589. return;
  40590. if (t0 < 0)
  40591. t0 = 0;
  40592. if (t0 > 1.0)
  40593. t0 = 1.0;
  40594. }
  40595. this._collisionPoint.copyFromFloats(0, 0, 0);
  40596. var found = false;
  40597. var t = 1.0;
  40598. if (!embeddedInPlane) {
  40599. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  40600. this.velocity.scaleToRef(t0, this._tempVector);
  40601. this._planeIntersectionPoint.addInPlace(this._tempVector);
  40602. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  40603. found = true;
  40604. t = t0;
  40605. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  40606. }
  40607. }
  40608. if (!found) {
  40609. var velocitySquaredLength = this.velocity.lengthSquared();
  40610. var a = velocitySquaredLength;
  40611. this.basePoint.subtractToRef(p1, this._tempVector);
  40612. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40613. var c = this._tempVector.lengthSquared() - 1.0;
  40614. var lowestRoot = getLowestRoot(a, b, c, t);
  40615. if (lowestRoot.found) {
  40616. t = lowestRoot.root;
  40617. found = true;
  40618. this._collisionPoint.copyFrom(p1);
  40619. }
  40620. this.basePoint.subtractToRef(p2, this._tempVector);
  40621. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40622. c = this._tempVector.lengthSquared() - 1.0;
  40623. lowestRoot = getLowestRoot(a, b, c, t);
  40624. if (lowestRoot.found) {
  40625. t = lowestRoot.root;
  40626. found = true;
  40627. this._collisionPoint.copyFrom(p2);
  40628. }
  40629. this.basePoint.subtractToRef(p3, this._tempVector);
  40630. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40631. c = this._tempVector.lengthSquared() - 1.0;
  40632. lowestRoot = getLowestRoot(a, b, c, t);
  40633. if (lowestRoot.found) {
  40634. t = lowestRoot.root;
  40635. found = true;
  40636. this._collisionPoint.copyFrom(p3);
  40637. }
  40638. p2.subtractToRef(p1, this._edge);
  40639. p1.subtractToRef(this.basePoint, this._baseToVertex);
  40640. var edgeSquaredLength = this._edge.lengthSquared();
  40641. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40642. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40643. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40644. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40645. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40646. lowestRoot = getLowestRoot(a, b, c, t);
  40647. if (lowestRoot.found) {
  40648. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40649. if (f >= 0.0 && f <= 1.0) {
  40650. t = lowestRoot.root;
  40651. found = true;
  40652. this._edge.scaleInPlace(f);
  40653. p1.addToRef(this._edge, this._collisionPoint);
  40654. }
  40655. }
  40656. p3.subtractToRef(p2, this._edge);
  40657. p2.subtractToRef(this.basePoint, this._baseToVertex);
  40658. edgeSquaredLength = this._edge.lengthSquared();
  40659. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40660. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40661. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40662. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40663. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40664. lowestRoot = getLowestRoot(a, b, c, t);
  40665. if (lowestRoot.found) {
  40666. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40667. if (f >= 0.0 && f <= 1.0) {
  40668. t = lowestRoot.root;
  40669. found = true;
  40670. this._edge.scaleInPlace(f);
  40671. p2.addToRef(this._edge, this._collisionPoint);
  40672. }
  40673. }
  40674. p1.subtractToRef(p3, this._edge);
  40675. p3.subtractToRef(this.basePoint, this._baseToVertex);
  40676. edgeSquaredLength = this._edge.lengthSquared();
  40677. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40678. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40679. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40680. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40681. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40682. lowestRoot = getLowestRoot(a, b, c, t);
  40683. if (lowestRoot.found) {
  40684. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40685. if (f >= 0.0 && f <= 1.0) {
  40686. t = lowestRoot.root;
  40687. found = true;
  40688. this._edge.scaleInPlace(f);
  40689. p3.addToRef(this._edge, this._collisionPoint);
  40690. }
  40691. }
  40692. }
  40693. if (found) {
  40694. var distToCollision = t * this.velocity.length();
  40695. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  40696. if (!this.intersectionPoint) {
  40697. this.intersectionPoint = this._collisionPoint.clone();
  40698. }
  40699. else {
  40700. this.intersectionPoint.copyFrom(this._collisionPoint);
  40701. }
  40702. this.nearestDistance = distToCollision;
  40703. this.collisionFound = true;
  40704. }
  40705. }
  40706. };
  40707. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  40708. for (var i = indexStart; i < indexEnd; i += 3) {
  40709. var p1 = pts[indices[i] - decal];
  40710. var p2 = pts[indices[i + 1] - decal];
  40711. var p3 = pts[indices[i + 2] - decal];
  40712. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  40713. }
  40714. };
  40715. Collider.prototype._getResponse = function (pos, vel) {
  40716. pos.addToRef(vel, this._destinationPoint);
  40717. vel.scaleInPlace((this.nearestDistance / vel.length()));
  40718. this.basePoint.addToRef(vel, pos);
  40719. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  40720. this._slidePlaneNormal.normalize();
  40721. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  40722. pos.addInPlace(this._displacementVector);
  40723. this.intersectionPoint.addInPlace(this._displacementVector);
  40724. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  40725. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  40726. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  40727. };
  40728. return Collider;
  40729. }());
  40730. BABYLON.Collider = Collider;
  40731. })(BABYLON || (BABYLON = {}));
  40732. //# sourceMappingURL=babylon.collider.js.map
  40733. var BABYLON;
  40734. (function (BABYLON) {
  40735. //WebWorker code will be inserted to this variable.
  40736. BABYLON.CollisionWorker = "";
  40737. var WorkerTaskType;
  40738. (function (WorkerTaskType) {
  40739. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  40740. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  40741. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  40742. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  40743. var WorkerReplyType;
  40744. (function (WorkerReplyType) {
  40745. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  40746. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  40747. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  40748. var CollisionCoordinatorWorker = (function () {
  40749. function CollisionCoordinatorWorker() {
  40750. var _this = this;
  40751. this._scaledPosition = BABYLON.Vector3.Zero();
  40752. this._scaledVelocity = BABYLON.Vector3.Zero();
  40753. this.onMeshUpdated = function (mesh) {
  40754. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  40755. };
  40756. this.onGeometryUpdated = function (geometry) {
  40757. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  40758. };
  40759. this._afterRender = function () {
  40760. if (!_this._init)
  40761. return;
  40762. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  40763. return;
  40764. }
  40765. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  40766. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  40767. if (_this._runningUpdated > 4) {
  40768. return;
  40769. }
  40770. ++_this._runningUpdated;
  40771. var payload = {
  40772. updatedMeshes: _this._addUpdateMeshesList,
  40773. updatedGeometries: _this._addUpdateGeometriesList,
  40774. removedGeometries: _this._toRemoveGeometryArray,
  40775. removedMeshes: _this._toRemoveMeshesArray
  40776. };
  40777. var message = {
  40778. payload: payload,
  40779. taskType: WorkerTaskType.UPDATE
  40780. };
  40781. var serializable = [];
  40782. for (var id in payload.updatedGeometries) {
  40783. if (payload.updatedGeometries.hasOwnProperty(id)) {
  40784. //prepare transferables
  40785. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  40786. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  40787. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  40788. }
  40789. }
  40790. _this._worker.postMessage(message, serializable);
  40791. _this._addUpdateMeshesList = {};
  40792. _this._addUpdateGeometriesList = {};
  40793. _this._toRemoveGeometryArray = [];
  40794. _this._toRemoveMeshesArray = [];
  40795. };
  40796. this._onMessageFromWorker = function (e) {
  40797. var returnData = e.data;
  40798. if (returnData.error != WorkerReplyType.SUCCESS) {
  40799. //TODO what errors can be returned from the worker?
  40800. BABYLON.Tools.Warn("error returned from worker!");
  40801. return;
  40802. }
  40803. switch (returnData.taskType) {
  40804. case WorkerTaskType.INIT:
  40805. _this._init = true;
  40806. //Update the worked with ALL of the scene's current state
  40807. _this._scene.meshes.forEach(function (mesh) {
  40808. _this.onMeshAdded(mesh);
  40809. });
  40810. _this._scene.getGeometries().forEach(function (geometry) {
  40811. _this.onGeometryAdded(geometry);
  40812. });
  40813. break;
  40814. case WorkerTaskType.UPDATE:
  40815. _this._runningUpdated--;
  40816. break;
  40817. case WorkerTaskType.COLLIDE:
  40818. _this._runningCollisionTask = false;
  40819. var returnPayload = returnData.payload;
  40820. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  40821. return;
  40822. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  40823. //cleanup
  40824. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  40825. break;
  40826. }
  40827. };
  40828. this._collisionsCallbackArray = [];
  40829. this._init = false;
  40830. this._runningUpdated = 0;
  40831. this._runningCollisionTask = false;
  40832. this._addUpdateMeshesList = {};
  40833. this._addUpdateGeometriesList = {};
  40834. this._toRemoveGeometryArray = [];
  40835. this._toRemoveMeshesArray = [];
  40836. }
  40837. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40838. if (!this._init)
  40839. return;
  40840. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  40841. return;
  40842. position.divideToRef(collider.radius, this._scaledPosition);
  40843. displacement.divideToRef(collider.radius, this._scaledVelocity);
  40844. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  40845. var payload = {
  40846. collider: {
  40847. position: this._scaledPosition.asArray(),
  40848. velocity: this._scaledVelocity.asArray(),
  40849. radius: collider.radius.asArray()
  40850. },
  40851. collisionId: collisionIndex,
  40852. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  40853. maximumRetry: maximumRetry
  40854. };
  40855. var message = {
  40856. payload: payload,
  40857. taskType: WorkerTaskType.COLLIDE
  40858. };
  40859. this._worker.postMessage(message);
  40860. };
  40861. CollisionCoordinatorWorker.prototype.init = function (scene) {
  40862. this._scene = scene;
  40863. this._scene.registerAfterRender(this._afterRender);
  40864. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  40865. this._worker = new Worker(workerUrl);
  40866. this._worker.onmessage = this._onMessageFromWorker;
  40867. var message = {
  40868. payload: {},
  40869. taskType: WorkerTaskType.INIT
  40870. };
  40871. this._worker.postMessage(message);
  40872. };
  40873. CollisionCoordinatorWorker.prototype.destroy = function () {
  40874. this._scene.unregisterAfterRender(this._afterRender);
  40875. this._worker.terminate();
  40876. };
  40877. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  40878. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  40879. this.onMeshUpdated(mesh);
  40880. };
  40881. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  40882. this._toRemoveMeshesArray.push(mesh.uniqueId);
  40883. };
  40884. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  40885. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  40886. geometry.onGeometryUpdated = this.onGeometryUpdated;
  40887. this.onGeometryUpdated(geometry);
  40888. };
  40889. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  40890. this._toRemoveGeometryArray.push(geometry.id);
  40891. };
  40892. return CollisionCoordinatorWorker;
  40893. }());
  40894. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  40895. var submeshes = [];
  40896. if (mesh.subMeshes) {
  40897. submeshes = mesh.subMeshes.map(function (sm, idx) {
  40898. return {
  40899. position: idx,
  40900. verticesStart: sm.verticesStart,
  40901. verticesCount: sm.verticesCount,
  40902. indexStart: sm.indexStart,
  40903. indexCount: sm.indexCount,
  40904. hasMaterial: !!sm.getMaterial(),
  40905. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40906. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  40907. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40908. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  40909. };
  40910. });
  40911. }
  40912. var geometryId = null;
  40913. if (mesh instanceof BABYLON.Mesh) {
  40914. geometryId = mesh.geometry ? mesh.geometry.id : null;
  40915. }
  40916. else if (mesh instanceof BABYLON.InstancedMesh) {
  40917. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  40918. }
  40919. return {
  40920. uniqueId: mesh.uniqueId,
  40921. id: mesh.id,
  40922. name: mesh.name,
  40923. geometryId: geometryId,
  40924. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40925. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  40926. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40927. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  40928. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  40929. subMeshes: submeshes,
  40930. checkCollisions: mesh.checkCollisions
  40931. };
  40932. };
  40933. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  40934. return {
  40935. id: geometry.id,
  40936. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  40937. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  40938. indices: new Uint32Array(geometry.getIndices() || []),
  40939. };
  40940. };
  40941. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  40942. var CollisionCoordinatorLegacy = (function () {
  40943. function CollisionCoordinatorLegacy() {
  40944. this._scaledPosition = BABYLON.Vector3.Zero();
  40945. this._scaledVelocity = BABYLON.Vector3.Zero();
  40946. this._finalPosition = BABYLON.Vector3.Zero();
  40947. }
  40948. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40949. position.divideToRef(collider.radius, this._scaledPosition);
  40950. displacement.divideToRef(collider.radius, this._scaledVelocity);
  40951. collider.collidedMesh = null;
  40952. collider.retry = 0;
  40953. collider.initialVelocity = this._scaledVelocity;
  40954. collider.initialPosition = this._scaledPosition;
  40955. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  40956. this._finalPosition.multiplyInPlace(collider.radius);
  40957. //run the callback
  40958. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  40959. };
  40960. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  40961. this._scene = scene;
  40962. };
  40963. CollisionCoordinatorLegacy.prototype.destroy = function () {
  40964. //Legacy need no destruction method.
  40965. };
  40966. //No update in legacy mode
  40967. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  40968. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  40969. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  40970. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  40971. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  40972. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  40973. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  40974. if (excludedMesh === void 0) { excludedMesh = null; }
  40975. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  40976. if (collider.retry >= maximumRetry) {
  40977. finalPosition.copyFrom(position);
  40978. return;
  40979. }
  40980. // Check if this is a mesh else camera or -1
  40981. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  40982. collider._initialize(position, velocity, closeDistance);
  40983. // Check all meshes
  40984. for (var index = 0; index < this._scene.meshes.length; index++) {
  40985. var mesh = this._scene.meshes[index];
  40986. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  40987. mesh._checkCollision(collider);
  40988. }
  40989. }
  40990. if (!collider.collisionFound) {
  40991. position.addToRef(velocity, finalPosition);
  40992. return;
  40993. }
  40994. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  40995. collider._getResponse(position, velocity);
  40996. }
  40997. if (velocity.length() <= closeDistance) {
  40998. finalPosition.copyFrom(position);
  40999. return;
  41000. }
  41001. collider.retry++;
  41002. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  41003. };
  41004. return CollisionCoordinatorLegacy;
  41005. }());
  41006. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  41007. })(BABYLON || (BABYLON = {}));
  41008. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  41009. var BABYLON;
  41010. (function (BABYLON) {
  41011. var Particle = (function () {
  41012. function Particle(particleSystem) {
  41013. this.particleSystem = particleSystem;
  41014. this.position = BABYLON.Vector3.Zero();
  41015. this.direction = BABYLON.Vector3.Zero();
  41016. this.color = new BABYLON.Color4(0, 0, 0, 0);
  41017. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  41018. this.lifeTime = 1.0;
  41019. this.age = 0;
  41020. this.size = 0;
  41021. this.angle = 0;
  41022. this.angularSpeed = 0;
  41023. this._currentFrameCounter = 0;
  41024. this.cellIndex = 0;
  41025. if (!this.particleSystem.isAnimationSheetEnabled) {
  41026. return;
  41027. }
  41028. this.cellIndex = this.particleSystem.startSpriteCellID;
  41029. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  41030. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  41031. }
  41032. else {
  41033. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  41034. }
  41035. }
  41036. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  41037. // (ageOffset / scaledUpdateSpeed) / available cells
  41038. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  41039. this._currentFrameCounter += scaledUpdateSpeed;
  41040. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  41041. this._currentFrameCounter = 0;
  41042. this.cellIndex++;
  41043. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  41044. this.cellIndex = this.particleSystem.endSpriteCellID;
  41045. }
  41046. }
  41047. };
  41048. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  41049. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  41050. this.cellIndex++;
  41051. this._currentFrameCounter = 0;
  41052. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  41053. if (this.particleSystem.spriteCellLoop) {
  41054. this.cellIndex = this.particleSystem.startSpriteCellID;
  41055. }
  41056. else {
  41057. this.cellIndex = this.particleSystem.endSpriteCellID;
  41058. }
  41059. }
  41060. }
  41061. else {
  41062. this._currentFrameCounter++;
  41063. }
  41064. };
  41065. Particle.prototype.copyTo = function (other) {
  41066. other.position.copyFrom(this.position);
  41067. other.direction.copyFrom(this.direction);
  41068. other.color.copyFrom(this.color);
  41069. other.colorStep.copyFrom(this.colorStep);
  41070. other.lifeTime = this.lifeTime;
  41071. other.age = this.age;
  41072. other.size = this.size;
  41073. other.angle = this.angle;
  41074. other.angularSpeed = this.angularSpeed;
  41075. other.particleSystem = this.particleSystem;
  41076. other.cellIndex = this.cellIndex;
  41077. };
  41078. return Particle;
  41079. }());
  41080. BABYLON.Particle = Particle;
  41081. })(BABYLON || (BABYLON = {}));
  41082. //# sourceMappingURL=babylon.particle.js.map
  41083. var BABYLON;
  41084. (function (BABYLON) {
  41085. var randomNumber = function (min, max) {
  41086. if (min === max) {
  41087. return (min);
  41088. }
  41089. var random = Math.random();
  41090. return ((random * (max - min)) + min);
  41091. };
  41092. var ParticleSystem = (function () {
  41093. // end of sheet animation
  41094. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  41095. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  41096. if (epsilon === void 0) { epsilon = 0.01; }
  41097. var _this = this;
  41098. this.name = name;
  41099. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  41100. // Members
  41101. this.animations = [];
  41102. this.renderingGroupId = 0;
  41103. this.emitter = null;
  41104. this.emitRate = 10;
  41105. this.manualEmitCount = -1;
  41106. this.updateSpeed = 0.01;
  41107. this.targetStopDuration = 0;
  41108. this.disposeOnStop = false;
  41109. this.minEmitPower = 1;
  41110. this.maxEmitPower = 1;
  41111. this.minLifeTime = 1;
  41112. this.maxLifeTime = 1;
  41113. this.minSize = 1;
  41114. this.maxSize = 1;
  41115. this.minAngularSpeed = 0;
  41116. this.maxAngularSpeed = 0;
  41117. this.layerMask = 0x0FFFFFFF;
  41118. this.customShader = null;
  41119. this.preventAutoStart = false;
  41120. /**
  41121. * An event triggered when the system is disposed.
  41122. * @type {BABYLON.Observable}
  41123. */
  41124. this.onDisposeObservable = new BABYLON.Observable();
  41125. this.onAnimationEnd = null;
  41126. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  41127. this.forceDepthWrite = false;
  41128. this.gravity = BABYLON.Vector3.Zero();
  41129. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  41130. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  41131. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  41132. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  41133. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  41134. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  41135. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  41136. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  41137. this.particles = new Array();
  41138. this._stockParticles = new Array();
  41139. this._newPartsExcess = 0;
  41140. this._vertexBuffers = {};
  41141. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  41142. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  41143. this._scaledDirection = BABYLON.Vector3.Zero();
  41144. this._scaledGravity = BABYLON.Vector3.Zero();
  41145. this._currentRenderId = -1;
  41146. this._started = false;
  41147. this._stopped = false;
  41148. this._actualFrame = 0;
  41149. // sheet animation
  41150. this.startSpriteCellID = 0;
  41151. this.endSpriteCellID = 0;
  41152. this.spriteCellLoop = true;
  41153. this.spriteCellChangeSpeed = 0;
  41154. this.spriteCellWidth = 0;
  41155. this.spriteCellHeight = 0;
  41156. this._vertexBufferSize = 11;
  41157. this.appendParticleVertexes = null;
  41158. this.id = name;
  41159. this._capacity = capacity;
  41160. this._epsilon = epsilon;
  41161. if (_isAnimationSheetEnabled) {
  41162. this._vertexBufferSize = 12;
  41163. }
  41164. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  41165. this._customEffect = customEffect;
  41166. scene.particleSystems.push(this);
  41167. this._createIndexBuffer();
  41168. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  41169. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  41170. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  41171. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  41172. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  41173. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  41174. if (this._isAnimationSheetEnabled) {
  41175. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  41176. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  41177. }
  41178. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  41179. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  41180. this._vertexBuffers["options"] = options;
  41181. // Default behaviors
  41182. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  41183. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  41184. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  41185. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  41186. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  41187. };
  41188. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  41189. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  41190. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  41191. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  41192. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  41193. };
  41194. this.updateFunction = function (particles) {
  41195. for (var index = 0; index < particles.length; index++) {
  41196. var particle = particles[index];
  41197. particle.age += _this._scaledUpdateSpeed;
  41198. if (particle.age >= particle.lifeTime) {
  41199. _this.recycleParticle(particle);
  41200. index--;
  41201. continue;
  41202. }
  41203. else {
  41204. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  41205. particle.color.addInPlace(_this._scaledColorStep);
  41206. if (particle.color.a < 0)
  41207. particle.color.a = 0;
  41208. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  41209. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  41210. particle.position.addInPlace(_this._scaledDirection);
  41211. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  41212. particle.direction.addInPlace(_this._scaledGravity);
  41213. if (_this._isAnimationSheetEnabled) {
  41214. particle.updateCellIndex(_this._scaledUpdateSpeed);
  41215. }
  41216. }
  41217. }
  41218. };
  41219. }
  41220. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  41221. set: function (callback) {
  41222. if (this._onDisposeObserver) {
  41223. this.onDisposeObservable.remove(this._onDisposeObserver);
  41224. }
  41225. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  41226. },
  41227. enumerable: true,
  41228. configurable: true
  41229. });
  41230. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  41231. get: function () {
  41232. return this._isAnimationSheetEnabled;
  41233. },
  41234. enumerable: true,
  41235. configurable: true
  41236. });
  41237. ParticleSystem.prototype._createIndexBuffer = function () {
  41238. var indices = [];
  41239. var index = 0;
  41240. for (var count = 0; count < this._capacity; count++) {
  41241. indices.push(index);
  41242. indices.push(index + 1);
  41243. indices.push(index + 2);
  41244. indices.push(index);
  41245. indices.push(index + 2);
  41246. indices.push(index + 3);
  41247. index += 4;
  41248. }
  41249. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  41250. };
  41251. ParticleSystem.prototype.recycleParticle = function (particle) {
  41252. var lastParticle = this.particles.pop();
  41253. if (lastParticle !== particle) {
  41254. lastParticle.copyTo(particle);
  41255. this._stockParticles.push(lastParticle);
  41256. }
  41257. };
  41258. ParticleSystem.prototype.getCapacity = function () {
  41259. return this._capacity;
  41260. };
  41261. ParticleSystem.prototype.isAlive = function () {
  41262. return this._alive;
  41263. };
  41264. ParticleSystem.prototype.isStarted = function () {
  41265. return this._started;
  41266. };
  41267. ParticleSystem.prototype.start = function () {
  41268. this._started = true;
  41269. this._stopped = false;
  41270. this._actualFrame = 0;
  41271. };
  41272. ParticleSystem.prototype.stop = function () {
  41273. this._stopped = true;
  41274. };
  41275. // animation sheet
  41276. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  41277. var offset = index * this._vertexBufferSize;
  41278. this._vertexData[offset] = particle.position.x;
  41279. this._vertexData[offset + 1] = particle.position.y;
  41280. this._vertexData[offset + 2] = particle.position.z;
  41281. this._vertexData[offset + 3] = particle.color.r;
  41282. this._vertexData[offset + 4] = particle.color.g;
  41283. this._vertexData[offset + 5] = particle.color.b;
  41284. this._vertexData[offset + 6] = particle.color.a;
  41285. this._vertexData[offset + 7] = particle.angle;
  41286. this._vertexData[offset + 8] = particle.size;
  41287. this._vertexData[offset + 9] = offsetX;
  41288. this._vertexData[offset + 10] = offsetY;
  41289. };
  41290. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  41291. if (offsetX === 0)
  41292. offsetX = this._epsilon;
  41293. else if (offsetX === 1)
  41294. offsetX = 1 - this._epsilon;
  41295. if (offsetY === 0)
  41296. offsetY = this._epsilon;
  41297. else if (offsetY === 1)
  41298. offsetY = 1 - this._epsilon;
  41299. var offset = index * this._vertexBufferSize;
  41300. this._vertexData[offset] = particle.position.x;
  41301. this._vertexData[offset + 1] = particle.position.y;
  41302. this._vertexData[offset + 2] = particle.position.z;
  41303. this._vertexData[offset + 3] = particle.color.r;
  41304. this._vertexData[offset + 4] = particle.color.g;
  41305. this._vertexData[offset + 5] = particle.color.b;
  41306. this._vertexData[offset + 6] = particle.color.a;
  41307. this._vertexData[offset + 7] = particle.angle;
  41308. this._vertexData[offset + 8] = particle.size;
  41309. this._vertexData[offset + 9] = offsetX;
  41310. this._vertexData[offset + 10] = offsetY;
  41311. this._vertexData[offset + 11] = particle.cellIndex;
  41312. };
  41313. ParticleSystem.prototype._update = function (newParticles) {
  41314. // Update current
  41315. this._alive = this.particles.length > 0;
  41316. this.updateFunction(this.particles);
  41317. // Add new ones
  41318. var worldMatrix;
  41319. if (this.emitter.position) {
  41320. var emitterMesh = this.emitter;
  41321. worldMatrix = emitterMesh.getWorldMatrix();
  41322. }
  41323. else {
  41324. var emitterPosition = this.emitter;
  41325. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  41326. }
  41327. var particle;
  41328. for (var index = 0; index < newParticles; index++) {
  41329. if (this.particles.length === this._capacity) {
  41330. break;
  41331. }
  41332. if (this._stockParticles.length !== 0) {
  41333. particle = this._stockParticles.pop();
  41334. particle.age = 0;
  41335. particle.cellIndex = this.startSpriteCellID;
  41336. }
  41337. else {
  41338. particle = new BABYLON.Particle(this);
  41339. }
  41340. this.particles.push(particle);
  41341. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  41342. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  41343. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  41344. particle.size = randomNumber(this.minSize, this.maxSize);
  41345. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  41346. this.startPositionFunction(worldMatrix, particle.position, particle);
  41347. var step = randomNumber(0, 1.0);
  41348. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  41349. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  41350. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  41351. }
  41352. };
  41353. ParticleSystem.prototype._getEffect = function () {
  41354. if (this._customEffect) {
  41355. return this._customEffect;
  41356. }
  41357. ;
  41358. var defines = [];
  41359. if (this._scene.clipPlane) {
  41360. defines.push("#define CLIPPLANE");
  41361. }
  41362. if (this._isAnimationSheetEnabled) {
  41363. defines.push("#define ANIMATESHEET");
  41364. }
  41365. // Effect
  41366. var join = defines.join("\n");
  41367. if (this._cachedDefines !== join) {
  41368. this._cachedDefines = join;
  41369. var attributesNamesOrOptions;
  41370. var effectCreationOption;
  41371. if (this._isAnimationSheetEnabled) {
  41372. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  41373. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  41374. }
  41375. else {
  41376. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  41377. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  41378. }
  41379. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  41380. }
  41381. return this._effect;
  41382. };
  41383. ParticleSystem.prototype.animate = function () {
  41384. if (!this._started)
  41385. return;
  41386. var effect = this._getEffect();
  41387. // Check
  41388. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  41389. return;
  41390. if (this._currentRenderId === this._scene.getRenderId()) {
  41391. return;
  41392. }
  41393. this._currentRenderId = this._scene.getRenderId();
  41394. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  41395. // determine the number of particles we need to create
  41396. var newParticles;
  41397. if (this.manualEmitCount > -1) {
  41398. newParticles = this.manualEmitCount;
  41399. this._newPartsExcess = 0;
  41400. this.manualEmitCount = 0;
  41401. }
  41402. else {
  41403. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  41404. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  41405. }
  41406. if (this._newPartsExcess > 1.0) {
  41407. newParticles += this._newPartsExcess >> 0;
  41408. this._newPartsExcess -= this._newPartsExcess >> 0;
  41409. }
  41410. this._alive = false;
  41411. if (!this._stopped) {
  41412. this._actualFrame += this._scaledUpdateSpeed;
  41413. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  41414. this.stop();
  41415. }
  41416. else {
  41417. newParticles = 0;
  41418. }
  41419. this._update(newParticles);
  41420. // Stopped?
  41421. if (this._stopped) {
  41422. if (!this._alive) {
  41423. this._started = false;
  41424. if (this.onAnimationEnd) {
  41425. this.onAnimationEnd();
  41426. }
  41427. if (this.disposeOnStop) {
  41428. this._scene._toBeDisposed.push(this);
  41429. }
  41430. }
  41431. }
  41432. // Animation sheet
  41433. if (this._isAnimationSheetEnabled) {
  41434. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  41435. }
  41436. else {
  41437. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  41438. }
  41439. // Update VBO
  41440. var offset = 0;
  41441. for (var index = 0; index < this.particles.length; index++) {
  41442. var particle = this.particles[index];
  41443. this.appendParticleVertexes(offset, particle);
  41444. offset += 4;
  41445. }
  41446. this._vertexBuffer.update(this._vertexData);
  41447. };
  41448. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  41449. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  41450. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  41451. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  41452. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  41453. };
  41454. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  41455. this._appendParticleVertex(offset++, particle, 0, 0);
  41456. this._appendParticleVertex(offset++, particle, 1, 0);
  41457. this._appendParticleVertex(offset++, particle, 1, 1);
  41458. this._appendParticleVertex(offset++, particle, 0, 1);
  41459. };
  41460. ParticleSystem.prototype.rebuild = function () {
  41461. this._createIndexBuffer();
  41462. this._vertexBuffer._rebuild();
  41463. };
  41464. ParticleSystem.prototype.render = function () {
  41465. var effect = this._getEffect();
  41466. // Check
  41467. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  41468. return 0;
  41469. var engine = this._scene.getEngine();
  41470. // Render
  41471. engine.enableEffect(effect);
  41472. engine.setState(false);
  41473. var viewMatrix = this._scene.getViewMatrix();
  41474. effect.setTexture("diffuseSampler", this.particleTexture);
  41475. effect.setMatrix("view", viewMatrix);
  41476. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  41477. if (this._isAnimationSheetEnabled) {
  41478. var baseSize = this.particleTexture.getBaseSize();
  41479. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  41480. }
  41481. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  41482. if (this._scene.clipPlane) {
  41483. var clipPlane = this._scene.clipPlane;
  41484. var invView = viewMatrix.clone();
  41485. invView.invert();
  41486. effect.setMatrix("invView", invView);
  41487. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41488. }
  41489. // VBOs
  41490. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  41491. // Draw order
  41492. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  41493. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  41494. }
  41495. else {
  41496. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41497. }
  41498. if (this.forceDepthWrite) {
  41499. engine.setDepthWrite(true);
  41500. }
  41501. engine.draw(true, 0, this.particles.length * 6);
  41502. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41503. return this.particles.length;
  41504. };
  41505. ParticleSystem.prototype.dispose = function () {
  41506. if (this._vertexBuffer) {
  41507. this._vertexBuffer.dispose();
  41508. this._vertexBuffer = null;
  41509. }
  41510. if (this._indexBuffer) {
  41511. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  41512. this._indexBuffer = null;
  41513. }
  41514. if (this.particleTexture) {
  41515. this.particleTexture.dispose();
  41516. this.particleTexture = null;
  41517. }
  41518. // Remove from scene
  41519. var index = this._scene.particleSystems.indexOf(this);
  41520. if (index > -1) {
  41521. this._scene.particleSystems.splice(index, 1);
  41522. }
  41523. // Callback
  41524. this.onDisposeObservable.notifyObservers(this);
  41525. this.onDisposeObservable.clear();
  41526. };
  41527. // Clone
  41528. ParticleSystem.prototype.clone = function (name, newEmitter) {
  41529. var custom = null;
  41530. var program = null;
  41531. if (this.customShader != null) {
  41532. program = this.customShader;
  41533. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  41534. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  41535. }
  41536. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  41537. result.customShader = program;
  41538. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  41539. if (newEmitter === undefined) {
  41540. newEmitter = this.emitter;
  41541. }
  41542. result.emitter = newEmitter;
  41543. if (this.particleTexture) {
  41544. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  41545. }
  41546. if (!this.preventAutoStart) {
  41547. result.start();
  41548. }
  41549. return result;
  41550. };
  41551. ParticleSystem.prototype.serialize = function () {
  41552. var serializationObject = {};
  41553. serializationObject.name = this.name;
  41554. serializationObject.id = this.id;
  41555. // Emitter
  41556. if (this.emitter.position) {
  41557. var emitterMesh = this.emitter;
  41558. serializationObject.emitterId = emitterMesh.id;
  41559. }
  41560. else {
  41561. var emitterPosition = this.emitter;
  41562. serializationObject.emitter = emitterPosition.asArray();
  41563. }
  41564. serializationObject.capacity = this.getCapacity();
  41565. if (this.particleTexture) {
  41566. serializationObject.textureName = this.particleTexture.name;
  41567. }
  41568. // Animations
  41569. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  41570. // Particle system
  41571. serializationObject.minAngularSpeed = this.minAngularSpeed;
  41572. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  41573. serializationObject.minSize = this.minSize;
  41574. serializationObject.maxSize = this.maxSize;
  41575. serializationObject.minEmitPower = this.minEmitPower;
  41576. serializationObject.maxEmitPower = this.maxEmitPower;
  41577. serializationObject.minLifeTime = this.minLifeTime;
  41578. serializationObject.maxLifeTime = this.maxLifeTime;
  41579. serializationObject.emitRate = this.emitRate;
  41580. serializationObject.minEmitBox = this.minEmitBox.asArray();
  41581. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  41582. serializationObject.gravity = this.gravity.asArray();
  41583. serializationObject.direction1 = this.direction1.asArray();
  41584. serializationObject.direction2 = this.direction2.asArray();
  41585. serializationObject.color1 = this.color1.asArray();
  41586. serializationObject.color2 = this.color2.asArray();
  41587. serializationObject.colorDead = this.colorDead.asArray();
  41588. serializationObject.updateSpeed = this.updateSpeed;
  41589. serializationObject.targetStopDuration = this.targetStopDuration;
  41590. serializationObject.textureMask = this.textureMask.asArray();
  41591. serializationObject.blendMode = this.blendMode;
  41592. serializationObject.customShader = this.customShader;
  41593. serializationObject.preventAutoStart = this.preventAutoStart;
  41594. return serializationObject;
  41595. };
  41596. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  41597. var name = parsedParticleSystem.name;
  41598. var custom = null;
  41599. var program = null;
  41600. if (parsedParticleSystem.customShader) {
  41601. program = parsedParticleSystem.customShader;
  41602. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  41603. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  41604. }
  41605. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  41606. particleSystem.customShader = program;
  41607. if (parsedParticleSystem.id) {
  41608. particleSystem.id = parsedParticleSystem.id;
  41609. }
  41610. // Auto start
  41611. if (parsedParticleSystem.preventAutoStart) {
  41612. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  41613. }
  41614. // Texture
  41615. if (parsedParticleSystem.textureName) {
  41616. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  41617. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  41618. }
  41619. // Emitter
  41620. if (parsedParticleSystem.emitterId) {
  41621. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  41622. }
  41623. else {
  41624. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  41625. }
  41626. // Animations
  41627. if (parsedParticleSystem.animations) {
  41628. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  41629. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  41630. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  41631. }
  41632. }
  41633. if (parsedParticleSystem.autoAnimate) {
  41634. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  41635. }
  41636. // Particle system
  41637. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  41638. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  41639. particleSystem.minSize = parsedParticleSystem.minSize;
  41640. particleSystem.maxSize = parsedParticleSystem.maxSize;
  41641. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  41642. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  41643. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  41644. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  41645. particleSystem.emitRate = parsedParticleSystem.emitRate;
  41646. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  41647. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  41648. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  41649. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  41650. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  41651. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  41652. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  41653. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  41654. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  41655. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  41656. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  41657. particleSystem.blendMode = parsedParticleSystem.blendMode;
  41658. if (!particleSystem.preventAutoStart) {
  41659. particleSystem.start();
  41660. }
  41661. return particleSystem;
  41662. };
  41663. return ParticleSystem;
  41664. }());
  41665. // Statics
  41666. ParticleSystem.BLENDMODE_ONEONE = 0;
  41667. ParticleSystem.BLENDMODE_STANDARD = 1;
  41668. BABYLON.ParticleSystem = ParticleSystem;
  41669. })(BABYLON || (BABYLON = {}));
  41670. //# sourceMappingURL=babylon.particleSystem.js.map
  41671. var BABYLON;
  41672. (function (BABYLON) {
  41673. var SolidParticle = (function () {
  41674. /**
  41675. * Creates a Solid Particle object.
  41676. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  41677. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  41678. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  41679. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  41680. * `shapeId` (integer) is the model shape identifier in the SPS.
  41681. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  41682. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  41683. */
  41684. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  41685. this.idx = 0; // particle global index
  41686. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  41687. this.position = BABYLON.Vector3.Zero(); // position
  41688. this.rotation = BABYLON.Vector3.Zero(); // rotation
  41689. this.scaling = BABYLON.Vector3.One(); // scaling
  41690. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  41691. this.velocity = BABYLON.Vector3.Zero(); // velocity
  41692. this.alive = true; // alive
  41693. this.isVisible = true; // visibility
  41694. this._pos = 0; // index of this particle in the global "positions" array
  41695. this.shapeId = 0; // model shape id
  41696. this.idxInShape = 0; // index of the particle in its shape id
  41697. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  41698. this.idx = particleIndex;
  41699. this._pos = positionIndex;
  41700. this._model = model;
  41701. this.shapeId = shapeId;
  41702. this.idxInShape = idxInShape;
  41703. this._sps = sps;
  41704. if (modelBoundingInfo) {
  41705. this._modelBoundingInfo = modelBoundingInfo;
  41706. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  41707. }
  41708. }
  41709. Object.defineProperty(SolidParticle.prototype, "scale", {
  41710. /**
  41711. * legacy support, changed scale to scaling
  41712. */
  41713. get: function () {
  41714. return this.scaling;
  41715. },
  41716. set: function (scale) {
  41717. this.scaling = scale;
  41718. },
  41719. enumerable: true,
  41720. configurable: true
  41721. });
  41722. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  41723. /**
  41724. * legacy support, changed quaternion to rotationQuaternion
  41725. */
  41726. get: function () {
  41727. return this.rotationQuaternion;
  41728. },
  41729. set: function (q) {
  41730. this.rotationQuaternion = q;
  41731. },
  41732. enumerable: true,
  41733. configurable: true
  41734. });
  41735. /**
  41736. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  41737. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  41738. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  41739. */
  41740. SolidParticle.prototype.intersectsMesh = function (target) {
  41741. if (!this._boundingInfo || !target._boundingInfo) {
  41742. return false;
  41743. }
  41744. if (this._sps._bSphereOnly) {
  41745. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  41746. }
  41747. return this._boundingInfo.intersects(target._boundingInfo, false);
  41748. };
  41749. return SolidParticle;
  41750. }());
  41751. BABYLON.SolidParticle = SolidParticle;
  41752. var ModelShape = (function () {
  41753. /**
  41754. * 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.
  41755. * SPS internal tool, don't use it manually.
  41756. */
  41757. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  41758. this.shapeID = id;
  41759. this._shape = shape;
  41760. this._shapeUV = shapeUV;
  41761. this._positionFunction = posFunction;
  41762. this._vertexFunction = vtxFunction;
  41763. }
  41764. return ModelShape;
  41765. }());
  41766. BABYLON.ModelShape = ModelShape;
  41767. })(BABYLON || (BABYLON = {}));
  41768. //# sourceMappingURL=babylon.solidParticle.js.map
  41769. var BABYLON;
  41770. (function (BABYLON) {
  41771. /**
  41772. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  41773. */
  41774. var SolidParticleSystem = (function () {
  41775. /**
  41776. * Creates a SPS (Solid Particle System) object.
  41777. * `name` (String) is the SPS name, this will be the underlying mesh name.
  41778. * `scene` (Scene) is the scene in which the SPS is added.
  41779. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  41780. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  41781. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  41782. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  41783. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  41784. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  41785. */
  41786. function SolidParticleSystem(name, scene, options) {
  41787. // public members
  41788. /**
  41789. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  41790. * Example : var p = SPS.particles[i];
  41791. */
  41792. this.particles = new Array();
  41793. /**
  41794. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  41795. */
  41796. this.nbParticles = 0;
  41797. /**
  41798. * If the particles must ever face the camera (default false). Useful for planar particles.
  41799. */
  41800. this.billboard = false;
  41801. /**
  41802. * Recompute normals when adding a shape
  41803. */
  41804. this.recomputeNormals = true;
  41805. /**
  41806. * This a counter ofr your own usage. It's not set by any SPS functions.
  41807. */
  41808. this.counter = 0;
  41809. /**
  41810. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  41811. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  41812. */
  41813. this.vars = {};
  41814. this._positions = new Array();
  41815. this._indices = new Array();
  41816. this._normals = new Array();
  41817. this._colors = new Array();
  41818. this._uvs = new Array();
  41819. this._index = 0; // indices index
  41820. this._updatable = true;
  41821. this._pickable = false;
  41822. this._isVisibilityBoxLocked = false;
  41823. this._alwaysVisible = false;
  41824. this._shapeCounter = 0;
  41825. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  41826. this._color = new BABYLON.Color4(0, 0, 0, 0);
  41827. this._computeParticleColor = true;
  41828. this._computeParticleTexture = true;
  41829. this._computeParticleRotation = true;
  41830. this._computeParticleVertex = false;
  41831. this._computeBoundingBox = false;
  41832. this._cam_axisZ = BABYLON.Vector3.Zero();
  41833. this._cam_axisY = BABYLON.Vector3.Zero();
  41834. this._cam_axisX = BABYLON.Vector3.Zero();
  41835. this._axisX = BABYLON.Axis.X;
  41836. this._axisY = BABYLON.Axis.Y;
  41837. this._axisZ = BABYLON.Axis.Z;
  41838. this._camDir = BABYLON.Vector3.Zero();
  41839. this._rotMatrix = new BABYLON.Matrix();
  41840. this._invertMatrix = new BABYLON.Matrix();
  41841. this._rotated = BABYLON.Vector3.Zero();
  41842. this._quaternion = new BABYLON.Quaternion();
  41843. this._vertex = BABYLON.Vector3.Zero();
  41844. this._normal = BABYLON.Vector3.Zero();
  41845. this._yaw = 0.0;
  41846. this._pitch = 0.0;
  41847. this._roll = 0.0;
  41848. this._halfroll = 0.0;
  41849. this._halfpitch = 0.0;
  41850. this._halfyaw = 0.0;
  41851. this._sinRoll = 0.0;
  41852. this._cosRoll = 0.0;
  41853. this._sinPitch = 0.0;
  41854. this._cosPitch = 0.0;
  41855. this._sinYaw = 0.0;
  41856. this._cosYaw = 0.0;
  41857. this._mustUnrotateFixedNormals = false;
  41858. this._minimum = BABYLON.Tmp.Vector3[0];
  41859. this._maximum = BABYLON.Tmp.Vector3[1];
  41860. this._scale = BABYLON.Tmp.Vector3[2];
  41861. this._translation = BABYLON.Tmp.Vector3[3];
  41862. this._minBbox = BABYLON.Tmp.Vector3[4];
  41863. this._maxBbox = BABYLON.Tmp.Vector3[5];
  41864. this._particlesIntersect = false;
  41865. this._bSphereOnly = false;
  41866. this._bSphereRadiusFactor = 1.0;
  41867. this.name = name;
  41868. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  41869. this._camera = scene.activeCamera;
  41870. this._pickable = options ? options.isPickable : false;
  41871. this._particlesIntersect = options ? options.particleIntersection : false;
  41872. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  41873. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  41874. if (options && options.updatable) {
  41875. this._updatable = options.updatable;
  41876. }
  41877. else {
  41878. this._updatable = true;
  41879. }
  41880. if (this._pickable) {
  41881. this.pickedParticles = [];
  41882. }
  41883. }
  41884. /**
  41885. * Builds the SPS underlying mesh. Returns a standard Mesh.
  41886. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  41887. */
  41888. SolidParticleSystem.prototype.buildMesh = function () {
  41889. if (this.nbParticles === 0) {
  41890. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  41891. this.addShape(triangle, 1);
  41892. triangle.dispose();
  41893. }
  41894. this._positions32 = new Float32Array(this._positions);
  41895. this._uvs32 = new Float32Array(this._uvs);
  41896. this._colors32 = new Float32Array(this._colors);
  41897. if (this.recomputeNormals) {
  41898. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  41899. }
  41900. this._normals32 = new Float32Array(this._normals);
  41901. this._fixedNormal32 = new Float32Array(this._normals);
  41902. if (this._mustUnrotateFixedNormals) {
  41903. this._unrotateFixedNormals();
  41904. }
  41905. var vertexData = new BABYLON.VertexData();
  41906. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  41907. vertexData.indices = this._indices;
  41908. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  41909. if (this._uvs32) {
  41910. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  41911. ;
  41912. }
  41913. if (this._colors32) {
  41914. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  41915. }
  41916. var mesh = new BABYLON.Mesh(this.name, this._scene);
  41917. vertexData.applyToMesh(mesh, this._updatable);
  41918. this.mesh = mesh;
  41919. this.mesh.isPickable = this._pickable;
  41920. // free memory
  41921. this._positions = null;
  41922. this._normals = null;
  41923. this._uvs = null;
  41924. this._colors = null;
  41925. if (!this._updatable) {
  41926. this.particles.length = 0;
  41927. }
  41928. return mesh;
  41929. };
  41930. /**
  41931. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  41932. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  41933. * Thus the particles generated from `digest()` have their property `position` set yet.
  41934. * `mesh` ( Mesh ) is the mesh to be digested
  41935. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  41936. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  41937. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  41938. */
  41939. SolidParticleSystem.prototype.digest = function (mesh, options) {
  41940. var size = (options && options.facetNb) || 1;
  41941. var number = (options && options.number);
  41942. var delta = (options && options.delta) || 0;
  41943. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41944. var meshInd = mesh.getIndices();
  41945. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41946. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41947. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41948. var f = 0; // facet counter
  41949. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  41950. // compute size from number
  41951. if (number) {
  41952. number = (number > totalFacets) ? totalFacets : number;
  41953. size = Math.round(totalFacets / number);
  41954. delta = 0;
  41955. }
  41956. else {
  41957. size = (size > totalFacets) ? totalFacets : size;
  41958. }
  41959. var facetPos = []; // submesh positions
  41960. var facetInd = []; // submesh indices
  41961. var facetUV = []; // submesh UV
  41962. var facetCol = []; // submesh colors
  41963. var barycenter = BABYLON.Tmp.Vector3[0];
  41964. var rand;
  41965. var sizeO = size;
  41966. while (f < totalFacets) {
  41967. size = sizeO + Math.floor((1 + delta) * Math.random());
  41968. if (f > totalFacets - size) {
  41969. size = totalFacets - f;
  41970. }
  41971. // reset temp arrays
  41972. facetPos.length = 0;
  41973. facetInd.length = 0;
  41974. facetUV.length = 0;
  41975. facetCol.length = 0;
  41976. // iterate over "size" facets
  41977. var fi = 0;
  41978. for (var j = f * 3; j < (f + size) * 3; j++) {
  41979. facetInd.push(fi);
  41980. var i = meshInd[j];
  41981. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  41982. if (meshUV) {
  41983. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  41984. }
  41985. if (meshCol) {
  41986. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  41987. }
  41988. fi++;
  41989. }
  41990. // create a model shape for each single particle
  41991. var idx = this.nbParticles;
  41992. var shape = this._posToShape(facetPos);
  41993. var shapeUV = this._uvsToShapeUV(facetUV);
  41994. // compute the barycenter of the shape
  41995. var v;
  41996. for (v = 0; v < shape.length; v++) {
  41997. barycenter.addInPlace(shape[v]);
  41998. }
  41999. barycenter.scaleInPlace(1 / shape.length);
  42000. // shift the shape from its barycenter to the origin
  42001. for (v = 0; v < shape.length; v++) {
  42002. shape[v].subtractInPlace(barycenter);
  42003. }
  42004. var bInfo;
  42005. if (this._particlesIntersect) {
  42006. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  42007. }
  42008. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  42009. // add the particle in the SPS
  42010. var currentPos = this._positions.length;
  42011. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  42012. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  42013. // initialize the particle position
  42014. this.particles[this.nbParticles].position.addInPlace(barycenter);
  42015. this._index += shape.length;
  42016. idx++;
  42017. this.nbParticles++;
  42018. this._shapeCounter++;
  42019. f += size;
  42020. }
  42021. return this;
  42022. };
  42023. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  42024. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  42025. var index = 0;
  42026. var idx = 0;
  42027. for (var p = 0; p < this.particles.length; p++) {
  42028. this._particle = this.particles[p];
  42029. this._shape = this._particle._model._shape;
  42030. if (this._particle.rotationQuaternion) {
  42031. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  42032. }
  42033. else {
  42034. this._yaw = this._particle.rotation.y;
  42035. this._pitch = this._particle.rotation.x;
  42036. this._roll = this._particle.rotation.z;
  42037. this._quaternionRotationYPR();
  42038. }
  42039. this._quaternionToRotationMatrix();
  42040. this._rotMatrix.invertToRef(this._invertMatrix);
  42041. for (var pt = 0; pt < this._shape.length; pt++) {
  42042. idx = index + pt * 3;
  42043. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  42044. this._fixedNormal32[idx] = this._normal.x;
  42045. this._fixedNormal32[idx + 1] = this._normal.y;
  42046. this._fixedNormal32[idx + 2] = this._normal.z;
  42047. }
  42048. index = idx + 3;
  42049. }
  42050. };
  42051. //reset copy
  42052. SolidParticleSystem.prototype._resetCopy = function () {
  42053. this._copy.position.x = 0;
  42054. this._copy.position.y = 0;
  42055. this._copy.position.z = 0;
  42056. this._copy.rotation.x = 0;
  42057. this._copy.rotation.y = 0;
  42058. this._copy.rotation.z = 0;
  42059. this._copy.rotationQuaternion = null;
  42060. this._copy.scaling.x = 1;
  42061. this._copy.scaling.y = 1;
  42062. this._copy.scaling.z = 1;
  42063. this._copy.uvs.x = 0;
  42064. this._copy.uvs.y = 0;
  42065. this._copy.uvs.z = 1;
  42066. this._copy.uvs.w = 1;
  42067. this._copy.color = null;
  42068. };
  42069. // _meshBuilder : inserts the shape model in the global SPS mesh
  42070. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  42071. var i;
  42072. var u = 0;
  42073. var c = 0;
  42074. var n = 0;
  42075. this._resetCopy();
  42076. if (options && options.positionFunction) {
  42077. options.positionFunction(this._copy, idx, idxInShape);
  42078. this._mustUnrotateFixedNormals = true;
  42079. }
  42080. if (this._copy.rotationQuaternion) {
  42081. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  42082. }
  42083. else {
  42084. this._yaw = this._copy.rotation.y;
  42085. this._pitch = this._copy.rotation.x;
  42086. this._roll = this._copy.rotation.z;
  42087. this._quaternionRotationYPR();
  42088. }
  42089. this._quaternionToRotationMatrix();
  42090. for (i = 0; i < shape.length; i++) {
  42091. this._vertex.x = shape[i].x;
  42092. this._vertex.y = shape[i].y;
  42093. this._vertex.z = shape[i].z;
  42094. if (options && options.vertexFunction) {
  42095. options.vertexFunction(this._copy, this._vertex, i);
  42096. }
  42097. this._vertex.x *= this._copy.scaling.x;
  42098. this._vertex.y *= this._copy.scaling.y;
  42099. this._vertex.z *= this._copy.scaling.z;
  42100. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  42101. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  42102. if (meshUV) {
  42103. 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);
  42104. u += 2;
  42105. }
  42106. if (this._copy.color) {
  42107. this._color = this._copy.color;
  42108. }
  42109. else if (meshCol && meshCol[c] !== undefined) {
  42110. this._color.r = meshCol[c];
  42111. this._color.g = meshCol[c + 1];
  42112. this._color.b = meshCol[c + 2];
  42113. this._color.a = meshCol[c + 3];
  42114. }
  42115. else {
  42116. this._color.r = 1;
  42117. this._color.g = 1;
  42118. this._color.b = 1;
  42119. this._color.a = 1;
  42120. }
  42121. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  42122. c += 4;
  42123. if (!this.recomputeNormals && meshNor) {
  42124. this._normal.x = meshNor[n];
  42125. this._normal.y = meshNor[n + 1];
  42126. this._normal.z = meshNor[n + 2];
  42127. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  42128. normals.push(this._normal.x, this._normal.y, this._normal.z);
  42129. n += 3;
  42130. }
  42131. }
  42132. for (i = 0; i < meshInd.length; i++) {
  42133. indices.push(p + meshInd[i]);
  42134. }
  42135. if (this._pickable) {
  42136. var nbfaces = meshInd.length / 3;
  42137. for (i = 0; i < nbfaces; i++) {
  42138. this.pickedParticles.push({ idx: idx, faceId: i });
  42139. }
  42140. }
  42141. return this._copy;
  42142. };
  42143. // returns a shape array from positions array
  42144. SolidParticleSystem.prototype._posToShape = function (positions) {
  42145. var shape = [];
  42146. for (var i = 0; i < positions.length; i += 3) {
  42147. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  42148. }
  42149. return shape;
  42150. };
  42151. // returns a shapeUV array from a Vector4 uvs
  42152. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  42153. var shapeUV = [];
  42154. if (uvs) {
  42155. for (var i = 0; i < uvs.length; i++)
  42156. shapeUV.push(uvs[i]);
  42157. }
  42158. return shapeUV;
  42159. };
  42160. // adds a new particle object in the particles array
  42161. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  42162. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  42163. this.particles.push(sp);
  42164. return sp;
  42165. };
  42166. /**
  42167. * Adds some particles to the SPS from the model shape. Returns the shape id.
  42168. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  42169. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  42170. * `nb` (positive integer) the number of particles to be created from this model
  42171. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  42172. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  42173. */
  42174. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  42175. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42176. var meshInd = mesh.getIndices();
  42177. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42178. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42179. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42180. var bbInfo;
  42181. if (this._particlesIntersect) {
  42182. bbInfo = mesh.getBoundingInfo();
  42183. }
  42184. var shape = this._posToShape(meshPos);
  42185. var shapeUV = this._uvsToShapeUV(meshUV);
  42186. var posfunc = options ? options.positionFunction : null;
  42187. var vtxfunc = options ? options.vertexFunction : null;
  42188. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  42189. // particles
  42190. var sp;
  42191. var currentCopy;
  42192. var idx = this.nbParticles;
  42193. for (var i = 0; i < nb; i++) {
  42194. var currentPos = this._positions.length;
  42195. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  42196. if (this._updatable) {
  42197. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  42198. sp.position.copyFrom(currentCopy.position);
  42199. sp.rotation.copyFrom(currentCopy.rotation);
  42200. if (currentCopy.rotationQuaternion) {
  42201. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  42202. }
  42203. if (currentCopy.color) {
  42204. sp.color.copyFrom(currentCopy.color);
  42205. }
  42206. sp.scaling.copyFrom(currentCopy.scaling);
  42207. sp.uvs.copyFrom(currentCopy.uvs);
  42208. }
  42209. this._index += shape.length;
  42210. idx++;
  42211. }
  42212. this.nbParticles += nb;
  42213. this._shapeCounter++;
  42214. return this._shapeCounter - 1;
  42215. };
  42216. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  42217. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  42218. this._resetCopy();
  42219. if (particle._model._positionFunction) {
  42220. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  42221. }
  42222. if (this._copy.rotationQuaternion) {
  42223. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  42224. }
  42225. else {
  42226. this._yaw = this._copy.rotation.y;
  42227. this._pitch = this._copy.rotation.x;
  42228. this._roll = this._copy.rotation.z;
  42229. this._quaternionRotationYPR();
  42230. }
  42231. this._quaternionToRotationMatrix();
  42232. this._shape = particle._model._shape;
  42233. for (var pt = 0; pt < this._shape.length; pt++) {
  42234. this._vertex.x = this._shape[pt].x;
  42235. this._vertex.y = this._shape[pt].y;
  42236. this._vertex.z = this._shape[pt].z;
  42237. if (particle._model._vertexFunction) {
  42238. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  42239. }
  42240. this._vertex.x *= this._copy.scaling.x;
  42241. this._vertex.y *= this._copy.scaling.y;
  42242. this._vertex.z *= this._copy.scaling.z;
  42243. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  42244. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  42245. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  42246. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  42247. }
  42248. particle.position.x = 0.0;
  42249. particle.position.y = 0.0;
  42250. particle.position.z = 0.0;
  42251. particle.rotation.x = 0.0;
  42252. particle.rotation.y = 0.0;
  42253. particle.rotation.z = 0.0;
  42254. particle.rotationQuaternion = null;
  42255. particle.scaling.x = 1.0;
  42256. particle.scaling.y = 1.0;
  42257. particle.scaling.z = 1.0;
  42258. };
  42259. /**
  42260. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  42261. * Returns the SPS.
  42262. */
  42263. SolidParticleSystem.prototype.rebuildMesh = function () {
  42264. for (var p = 0; p < this.particles.length; p++) {
  42265. this._rebuildParticle(this.particles[p]);
  42266. }
  42267. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42268. return this;
  42269. };
  42270. /**
  42271. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  42272. * This method calls `updateParticle()` for each particle of the SPS.
  42273. * For an animated SPS, it is usually called within the render loop.
  42274. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  42275. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  42276. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  42277. * Returns the SPS.
  42278. */
  42279. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  42280. if (start === void 0) { start = 0; }
  42281. if (end === void 0) { end = this.nbParticles - 1; }
  42282. if (update === void 0) { update = true; }
  42283. if (!this._updatable) {
  42284. return;
  42285. }
  42286. // custom beforeUpdate
  42287. this.beforeUpdateParticles(start, end, update);
  42288. this._cam_axisX.x = 1.0;
  42289. this._cam_axisX.y = 0.0;
  42290. this._cam_axisX.z = 0.0;
  42291. this._cam_axisY.x = 0.0;
  42292. this._cam_axisY.y = 1.0;
  42293. this._cam_axisY.z = 0.0;
  42294. this._cam_axisZ.x = 0.0;
  42295. this._cam_axisZ.y = 0.0;
  42296. this._cam_axisZ.z = 1.0;
  42297. // if the particles will always face the camera
  42298. if (this.billboard) {
  42299. this.mesh.computeWorldMatrix(true);
  42300. // compute the camera position and un-rotate it by the current mesh rotation
  42301. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  42302. this._quaternionToRotationMatrix();
  42303. this._rotMatrix.invertToRef(this._invertMatrix);
  42304. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  42305. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  42306. this._cam_axisZ.normalize();
  42307. // same for camera up vector extracted from the cam view matrix
  42308. var view = this._camera.getViewMatrix(true);
  42309. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  42310. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  42311. this._cam_axisY.normalize();
  42312. this._cam_axisX.normalize();
  42313. }
  42314. }
  42315. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  42316. var idx = 0; // current position index in the global array positions32
  42317. var index = 0; // position start index in the global array positions32 of the current particle
  42318. var colidx = 0; // current color index in the global array colors32
  42319. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  42320. var uvidx = 0; // current uv index in the global array uvs32
  42321. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  42322. var pt = 0; // current index in the particle model shape
  42323. if (this.mesh.isFacetDataEnabled) {
  42324. this._computeBoundingBox = true;
  42325. }
  42326. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  42327. if (this._computeBoundingBox) {
  42328. if (start == 0 && end == this.nbParticles - 1) {
  42329. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  42330. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  42331. }
  42332. else {
  42333. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  42334. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  42335. }
  42336. }
  42337. // particle loop
  42338. index = this.particles[start]._pos;
  42339. var vpos = (index / 3) | 0;
  42340. colorIndex = vpos * 4;
  42341. uvIndex = vpos * 2;
  42342. for (var p = start; p <= end; p++) {
  42343. this._particle = this.particles[p];
  42344. this._shape = this._particle._model._shape;
  42345. this._shapeUV = this._particle._model._shapeUV;
  42346. // call to custom user function to update the particle properties
  42347. this.updateParticle(this._particle);
  42348. // skip the computations for inactive or already invisible particles
  42349. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  42350. // increment indexes for the next particle
  42351. pt = this._shape.length;
  42352. index += pt * 3;
  42353. colorIndex += pt * 4;
  42354. uvIndex += pt * 2;
  42355. continue;
  42356. }
  42357. if (this._particle.isVisible) {
  42358. this._particle._stillInvisible = false; // un-mark permanent invisibility
  42359. // particle rotation matrix
  42360. if (this.billboard) {
  42361. this._particle.rotation.x = 0.0;
  42362. this._particle.rotation.y = 0.0;
  42363. }
  42364. if (this._computeParticleRotation || this.billboard) {
  42365. if (this._particle.rotationQuaternion) {
  42366. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  42367. }
  42368. else {
  42369. this._yaw = this._particle.rotation.y;
  42370. this._pitch = this._particle.rotation.x;
  42371. this._roll = this._particle.rotation.z;
  42372. this._quaternionRotationYPR();
  42373. }
  42374. this._quaternionToRotationMatrix();
  42375. }
  42376. // particle vertex loop
  42377. for (pt = 0; pt < this._shape.length; pt++) {
  42378. idx = index + pt * 3;
  42379. colidx = colorIndex + pt * 4;
  42380. uvidx = uvIndex + pt * 2;
  42381. this._vertex.x = this._shape[pt].x;
  42382. this._vertex.y = this._shape[pt].y;
  42383. this._vertex.z = this._shape[pt].z;
  42384. if (this._computeParticleVertex) {
  42385. this.updateParticleVertex(this._particle, this._vertex, pt);
  42386. }
  42387. // positions
  42388. this._vertex.x *= this._particle.scaling.x;
  42389. this._vertex.y *= this._particle.scaling.y;
  42390. this._vertex.z *= this._particle.scaling.z;
  42391. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  42392. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  42393. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  42394. 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;
  42395. 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;
  42396. 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;
  42397. if (this._computeBoundingBox) {
  42398. if (this._positions32[idx] < this._minimum.x) {
  42399. this._minimum.x = this._positions32[idx];
  42400. }
  42401. if (this._positions32[idx] > this._maximum.x) {
  42402. this._maximum.x = this._positions32[idx];
  42403. }
  42404. if (this._positions32[idx + 1] < this._minimum.y) {
  42405. this._minimum.y = this._positions32[idx + 1];
  42406. }
  42407. if (this._positions32[idx + 1] > this._maximum.y) {
  42408. this._maximum.y = this._positions32[idx + 1];
  42409. }
  42410. if (this._positions32[idx + 2] < this._minimum.z) {
  42411. this._minimum.z = this._positions32[idx + 2];
  42412. }
  42413. if (this._positions32[idx + 2] > this._maximum.z) {
  42414. this._maximum.z = this._positions32[idx + 2];
  42415. }
  42416. }
  42417. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  42418. if (!this._computeParticleVertex) {
  42419. this._normal.x = this._fixedNormal32[idx];
  42420. this._normal.y = this._fixedNormal32[idx + 1];
  42421. this._normal.z = this._fixedNormal32[idx + 2];
  42422. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  42423. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  42424. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  42425. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  42426. 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;
  42427. 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;
  42428. }
  42429. if (this._computeParticleColor) {
  42430. this._colors32[colidx] = this._particle.color.r;
  42431. this._colors32[colidx + 1] = this._particle.color.g;
  42432. this._colors32[colidx + 2] = this._particle.color.b;
  42433. this._colors32[colidx + 3] = this._particle.color.a;
  42434. }
  42435. if (this._computeParticleTexture) {
  42436. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  42437. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  42438. }
  42439. }
  42440. }
  42441. else {
  42442. this._particle._stillInvisible = true; // mark the particle as invisible
  42443. for (pt = 0; pt < this._shape.length; pt++) {
  42444. idx = index + pt * 3;
  42445. colidx = colorIndex + pt * 4;
  42446. uvidx = uvIndex + pt * 2;
  42447. this._positions32[idx] = 0.0;
  42448. this._positions32[idx + 1] = 0.0;
  42449. this._positions32[idx + 2] = 0.0;
  42450. this._normals32[idx] = 0.0;
  42451. this._normals32[idx + 1] = 0.0;
  42452. this._normals32[idx + 2] = 0.0;
  42453. if (this._computeParticleColor) {
  42454. this._colors32[colidx] = this._particle.color.r;
  42455. this._colors32[colidx + 1] = this._particle.color.g;
  42456. this._colors32[colidx + 2] = this._particle.color.b;
  42457. this._colors32[colidx + 3] = this._particle.color.a;
  42458. }
  42459. if (this._computeParticleTexture) {
  42460. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  42461. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  42462. }
  42463. }
  42464. }
  42465. // if the particle intersections must be computed : update the bbInfo
  42466. if (this._particlesIntersect) {
  42467. var bInfo = this._particle._boundingInfo;
  42468. var bBox = bInfo.boundingBox;
  42469. var bSphere = bInfo.boundingSphere;
  42470. if (!this._bSphereOnly) {
  42471. // place, scale and rotate the particle bbox within the SPS local system, then update it
  42472. for (var b = 0; b < bBox.vectors.length; b++) {
  42473. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  42474. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  42475. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  42476. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  42477. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  42478. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  42479. 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;
  42480. 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;
  42481. 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;
  42482. }
  42483. bBox._update(this.mesh._worldMatrix);
  42484. }
  42485. // place and scale the particle bouding sphere in the SPS local system, then update it
  42486. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  42487. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  42488. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  42489. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  42490. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  42491. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  42492. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  42493. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  42494. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  42495. 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));
  42496. bSphere._update(this.mesh._worldMatrix);
  42497. }
  42498. // increment indexes for the next particle
  42499. index = idx + 3;
  42500. colorIndex = colidx + 4;
  42501. uvIndex = uvidx + 2;
  42502. }
  42503. // if the VBO must be updated
  42504. if (update) {
  42505. if (this._computeParticleColor) {
  42506. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  42507. }
  42508. if (this._computeParticleTexture) {
  42509. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  42510. }
  42511. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42512. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  42513. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  42514. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  42515. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  42516. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  42517. for (var i = 0; i < this._normals32.length; i++) {
  42518. this._fixedNormal32[i] = this._normals32[i];
  42519. }
  42520. }
  42521. if (!this.mesh.areNormalsFrozen) {
  42522. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  42523. }
  42524. }
  42525. }
  42526. if (this._computeBoundingBox) {
  42527. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  42528. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  42529. }
  42530. this.afterUpdateParticles(start, end, update);
  42531. return this;
  42532. };
  42533. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  42534. this._halfroll = this._roll * 0.5;
  42535. this._halfpitch = this._pitch * 0.5;
  42536. this._halfyaw = this._yaw * 0.5;
  42537. this._sinRoll = Math.sin(this._halfroll);
  42538. this._cosRoll = Math.cos(this._halfroll);
  42539. this._sinPitch = Math.sin(this._halfpitch);
  42540. this._cosPitch = Math.cos(this._halfpitch);
  42541. this._sinYaw = Math.sin(this._halfyaw);
  42542. this._cosYaw = Math.cos(this._halfyaw);
  42543. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  42544. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  42545. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  42546. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  42547. };
  42548. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  42549. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  42550. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  42551. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  42552. this._rotMatrix.m[3] = 0;
  42553. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  42554. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  42555. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  42556. this._rotMatrix.m[7] = 0;
  42557. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  42558. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  42559. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  42560. this._rotMatrix.m[11] = 0;
  42561. this._rotMatrix.m[12] = 0;
  42562. this._rotMatrix.m[13] = 0;
  42563. this._rotMatrix.m[14] = 0;
  42564. this._rotMatrix.m[15] = 1.0;
  42565. };
  42566. /**
  42567. * Disposes the SPS.
  42568. * Returns nothing.
  42569. */
  42570. SolidParticleSystem.prototype.dispose = function () {
  42571. this.mesh.dispose();
  42572. this.vars = null;
  42573. // drop references to internal big arrays for the GC
  42574. this._positions = null;
  42575. this._indices = null;
  42576. this._normals = null;
  42577. this._uvs = null;
  42578. this._colors = null;
  42579. this._positions32 = null;
  42580. this._normals32 = null;
  42581. this._fixedNormal32 = null;
  42582. this._uvs32 = null;
  42583. this._colors32 = null;
  42584. this.pickedParticles = null;
  42585. };
  42586. /**
  42587. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  42588. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42589. * Returns the SPS.
  42590. */
  42591. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  42592. if (!this._isVisibilityBoxLocked) {
  42593. this.mesh.refreshBoundingInfo();
  42594. }
  42595. return this;
  42596. };
  42597. /**
  42598. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  42599. * @param size the size (float) of the visibility box
  42600. * note : this doesn't lock the SPS mesh bounding box.
  42601. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42602. */
  42603. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  42604. var vis = size / 2;
  42605. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  42606. };
  42607. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  42608. // getter and setter
  42609. get: function () {
  42610. return this._alwaysVisible;
  42611. },
  42612. /**
  42613. * Sets the SPS as always visible or not
  42614. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42615. */
  42616. set: function (val) {
  42617. this._alwaysVisible = val;
  42618. this.mesh.alwaysSelectAsActiveMesh = val;
  42619. },
  42620. enumerable: true,
  42621. configurable: true
  42622. });
  42623. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  42624. get: function () {
  42625. return this._isVisibilityBoxLocked;
  42626. },
  42627. /**
  42628. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  42629. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42630. */
  42631. set: function (val) {
  42632. this._isVisibilityBoxLocked = val;
  42633. this.mesh.getBoundingInfo().isLocked = val;
  42634. },
  42635. enumerable: true,
  42636. configurable: true
  42637. });
  42638. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  42639. // getters
  42640. get: function () {
  42641. return this._computeParticleRotation;
  42642. },
  42643. // Optimizer setters
  42644. /**
  42645. * Tells to `setParticles()` to compute the particle rotations or not.
  42646. * Default value : true. The SPS is faster when it's set to false.
  42647. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  42648. */
  42649. set: function (val) {
  42650. this._computeParticleRotation = val;
  42651. },
  42652. enumerable: true,
  42653. configurable: true
  42654. });
  42655. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  42656. get: function () {
  42657. return this._computeParticleColor;
  42658. },
  42659. /**
  42660. * Tells to `setParticles()` to compute the particle colors or not.
  42661. * Default value : true. The SPS is faster when it's set to false.
  42662. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  42663. */
  42664. set: function (val) {
  42665. this._computeParticleColor = val;
  42666. },
  42667. enumerable: true,
  42668. configurable: true
  42669. });
  42670. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  42671. get: function () {
  42672. return this._computeParticleTexture;
  42673. },
  42674. /**
  42675. * Tells to `setParticles()` to compute the particle textures or not.
  42676. * Default value : true. The SPS is faster when it's set to false.
  42677. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  42678. */
  42679. set: function (val) {
  42680. this._computeParticleTexture = val;
  42681. },
  42682. enumerable: true,
  42683. configurable: true
  42684. });
  42685. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  42686. get: function () {
  42687. return this._computeParticleVertex;
  42688. },
  42689. /**
  42690. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  42691. * Default value : false. The SPS is faster when it's set to false.
  42692. * Note : the particle custom vertex positions aren't stored values.
  42693. */
  42694. set: function (val) {
  42695. this._computeParticleVertex = val;
  42696. },
  42697. enumerable: true,
  42698. configurable: true
  42699. });
  42700. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  42701. get: function () {
  42702. return this._computeBoundingBox;
  42703. },
  42704. /**
  42705. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  42706. */
  42707. set: function (val) {
  42708. this._computeBoundingBox = val;
  42709. },
  42710. enumerable: true,
  42711. configurable: true
  42712. });
  42713. // =======================================================================
  42714. // Particle behavior logic
  42715. // these following methods may be overwritten by the user to fit his needs
  42716. /**
  42717. * This function does nothing. It may be overwritten to set all the particle first values.
  42718. * The SPS doesn't call this function, you may have to call it by your own.
  42719. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42720. */
  42721. SolidParticleSystem.prototype.initParticles = function () {
  42722. };
  42723. /**
  42724. * This function does nothing. It may be overwritten to recycle a particle.
  42725. * The SPS doesn't call this function, you may have to call it by your own.
  42726. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42727. */
  42728. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  42729. return particle;
  42730. };
  42731. /**
  42732. * Updates a particle : this function should be overwritten by the user.
  42733. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  42734. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42735. * ex : just set a particle position or velocity and recycle conditions
  42736. */
  42737. SolidParticleSystem.prototype.updateParticle = function (particle) {
  42738. return particle;
  42739. };
  42740. /**
  42741. * Updates a vertex of a particle : it can be overwritten by the user.
  42742. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  42743. * @param particle the current particle
  42744. * @param vertex the current index of the current particle
  42745. * @param pt the index of the current vertex in the particle shape
  42746. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  42747. * ex : just set a vertex particle position
  42748. */
  42749. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  42750. return vertex;
  42751. };
  42752. /**
  42753. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  42754. * This does nothing and may be overwritten by the user.
  42755. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42756. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42757. * @param update the boolean update value actually passed to setParticles()
  42758. */
  42759. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  42760. };
  42761. /**
  42762. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  42763. * This will be passed three parameters.
  42764. * This does nothing and may be overwritten by the user.
  42765. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42766. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42767. * @param update the boolean update value actually passed to setParticles()
  42768. */
  42769. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  42770. };
  42771. return SolidParticleSystem;
  42772. }());
  42773. BABYLON.SolidParticleSystem = SolidParticleSystem;
  42774. })(BABYLON || (BABYLON = {}));
  42775. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  42776. /// <reference path="babylon.mesh.ts" />
  42777. var BABYLON;
  42778. (function (BABYLON) {
  42779. var GroundMesh = (function (_super) {
  42780. __extends(GroundMesh, _super);
  42781. function GroundMesh(name, scene) {
  42782. var _this = _super.call(this, name, scene) || this;
  42783. _this.generateOctree = false;
  42784. _this._worldInverse = new BABYLON.Matrix();
  42785. return _this;
  42786. }
  42787. GroundMesh.prototype.getClassName = function () {
  42788. return "GroundMesh";
  42789. };
  42790. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  42791. get: function () {
  42792. return Math.min(this._subdivisionsX, this._subdivisionsY);
  42793. },
  42794. enumerable: true,
  42795. configurable: true
  42796. });
  42797. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  42798. get: function () {
  42799. return this._subdivisionsX;
  42800. },
  42801. enumerable: true,
  42802. configurable: true
  42803. });
  42804. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  42805. get: function () {
  42806. return this._subdivisionsY;
  42807. },
  42808. enumerable: true,
  42809. configurable: true
  42810. });
  42811. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  42812. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  42813. this._subdivisionsX = chunksCount;
  42814. this._subdivisionsY = chunksCount;
  42815. this.subdivide(chunksCount);
  42816. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  42817. };
  42818. /**
  42819. * Returns a height (y) value in the Worl system :
  42820. * the ground altitude at the coordinates (x, z) expressed in the World system.
  42821. * Returns the ground y position if (x, z) are outside the ground surface.
  42822. */
  42823. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  42824. var world = this.getWorldMatrix();
  42825. var invMat = BABYLON.Tmp.Matrix[5];
  42826. world.invertToRef(invMat);
  42827. var tmpVect = BABYLON.Tmp.Vector3[8];
  42828. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  42829. x = tmpVect.x;
  42830. z = tmpVect.z;
  42831. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42832. return this.position.y;
  42833. }
  42834. if (!this._heightQuads || this._heightQuads.length == 0) {
  42835. this._initHeightQuads();
  42836. this._computeHeightQuads();
  42837. }
  42838. var facet = this._getFacetAt(x, z);
  42839. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  42840. // return y in the World system
  42841. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  42842. return tmpVect.y;
  42843. };
  42844. /**
  42845. * Returns a normalized vector (Vector3) orthogonal to the ground
  42846. * at the ground coordinates (x, z) expressed in the World system.
  42847. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  42848. */
  42849. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  42850. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  42851. this.getNormalAtCoordinatesToRef(x, z, normal);
  42852. return normal;
  42853. };
  42854. /**
  42855. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  42856. * at the ground coordinates (x, z) expressed in the World system.
  42857. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  42858. * Returns the GroundMesh.
  42859. */
  42860. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  42861. var world = this.getWorldMatrix();
  42862. var tmpMat = BABYLON.Tmp.Matrix[5];
  42863. world.invertToRef(tmpMat);
  42864. var tmpVect = BABYLON.Tmp.Vector3[8];
  42865. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  42866. x = tmpVect.x;
  42867. z = tmpVect.z;
  42868. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42869. return this;
  42870. }
  42871. if (!this._heightQuads || this._heightQuads.length == 0) {
  42872. this._initHeightQuads();
  42873. this._computeHeightQuads();
  42874. }
  42875. var facet = this._getFacetAt(x, z);
  42876. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  42877. return this;
  42878. };
  42879. /**
  42880. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  42881. * if the ground has been updated.
  42882. * This can be used in the render loop.
  42883. * Returns the GroundMesh.
  42884. */
  42885. GroundMesh.prototype.updateCoordinateHeights = function () {
  42886. if (!this._heightQuads || this._heightQuads.length == 0) {
  42887. this._initHeightQuads();
  42888. }
  42889. this._computeHeightQuads();
  42890. return this;
  42891. };
  42892. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  42893. GroundMesh.prototype._getFacetAt = function (x, z) {
  42894. // retrieve col and row from x, z coordinates in the ground local system
  42895. var subdivisionsX = this._subdivisionsX;
  42896. var subdivisionsY = this._subdivisionsY;
  42897. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  42898. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  42899. var quad = this._heightQuads[row * this._subdivisionsX + col];
  42900. var facet;
  42901. if (z < quad.slope.x * x + quad.slope.y) {
  42902. facet = quad.facet1;
  42903. }
  42904. else {
  42905. facet = quad.facet2;
  42906. }
  42907. return facet;
  42908. };
  42909. // Creates and populates the heightMap array with "facet" elements :
  42910. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  42911. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42912. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42913. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42914. // Returns the GroundMesh.
  42915. GroundMesh.prototype._initHeightQuads = function () {
  42916. var subdivisionsX = this._subdivisionsX;
  42917. var subdivisionsY = this._subdivisionsY;
  42918. this._heightQuads = new Array();
  42919. for (var row = 0; row < subdivisionsY; row++) {
  42920. for (var col = 0; col < subdivisionsX; col++) {
  42921. 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) };
  42922. this._heightQuads[row * subdivisionsX + col] = quad;
  42923. }
  42924. }
  42925. return this;
  42926. };
  42927. // Compute each quad element values and update the the heightMap array :
  42928. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42929. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42930. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42931. // Returns the GroundMesh.
  42932. GroundMesh.prototype._computeHeightQuads = function () {
  42933. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42934. var v1 = BABYLON.Tmp.Vector3[3];
  42935. var v2 = BABYLON.Tmp.Vector3[2];
  42936. var v3 = BABYLON.Tmp.Vector3[1];
  42937. var v4 = BABYLON.Tmp.Vector3[0];
  42938. var v1v2 = BABYLON.Tmp.Vector3[4];
  42939. var v1v3 = BABYLON.Tmp.Vector3[5];
  42940. var v1v4 = BABYLON.Tmp.Vector3[6];
  42941. var norm1 = BABYLON.Tmp.Vector3[7];
  42942. var norm2 = BABYLON.Tmp.Vector3[8];
  42943. var i = 0;
  42944. var j = 0;
  42945. var k = 0;
  42946. var cd = 0; // 2D slope coefficient : z = cd * x + h
  42947. var h = 0;
  42948. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  42949. var d2 = 0;
  42950. var subdivisionsX = this._subdivisionsX;
  42951. var subdivisionsY = this._subdivisionsY;
  42952. for (var row = 0; row < subdivisionsY; row++) {
  42953. for (var col = 0; col < subdivisionsX; col++) {
  42954. i = col * 3;
  42955. j = row * (subdivisionsX + 1) * 3;
  42956. k = (row + 1) * (subdivisionsX + 1) * 3;
  42957. v1.x = positions[j + i];
  42958. v1.y = positions[j + i + 1];
  42959. v1.z = positions[j + i + 2];
  42960. v2.x = positions[j + i + 3];
  42961. v2.y = positions[j + i + 4];
  42962. v2.z = positions[j + i + 5];
  42963. v3.x = positions[k + i];
  42964. v3.y = positions[k + i + 1];
  42965. v3.z = positions[k + i + 2];
  42966. v4.x = positions[k + i + 3];
  42967. v4.y = positions[k + i + 4];
  42968. v4.z = positions[k + i + 5];
  42969. // 2D slope V1V4
  42970. cd = (v4.z - v1.z) / (v4.x - v1.x);
  42971. h = v1.z - cd * v1.x; // v1 belongs to the slope
  42972. // facet equations :
  42973. // we compute each facet normal vector
  42974. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  42975. // we compute the value d by applying the equation to v1 which belongs to the plane
  42976. // then we store the facet equation in a Vector4
  42977. v2.subtractToRef(v1, v1v2);
  42978. v3.subtractToRef(v1, v1v3);
  42979. v4.subtractToRef(v1, v1v4);
  42980. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  42981. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  42982. norm1.normalize();
  42983. norm2.normalize();
  42984. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  42985. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  42986. var quad = this._heightQuads[row * subdivisionsX + col];
  42987. quad.slope.copyFromFloats(cd, h);
  42988. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  42989. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  42990. }
  42991. }
  42992. return this;
  42993. };
  42994. GroundMesh.prototype.serialize = function (serializationObject) {
  42995. _super.prototype.serialize.call(this, serializationObject);
  42996. serializationObject.subdivisionsX = this._subdivisionsX;
  42997. serializationObject.subdivisionsY = this._subdivisionsY;
  42998. serializationObject.minX = this._minX;
  42999. serializationObject.maxX = this._maxX;
  43000. serializationObject.minZ = this._minZ;
  43001. serializationObject.maxZ = this._maxZ;
  43002. serializationObject.width = this._width;
  43003. serializationObject.height = this._height;
  43004. };
  43005. GroundMesh.Parse = function (parsedMesh, scene) {
  43006. var result = new GroundMesh(parsedMesh.name, scene);
  43007. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  43008. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  43009. result._minX = parsedMesh.minX;
  43010. result._maxX = parsedMesh.maxX;
  43011. result._minZ = parsedMesh.minZ;
  43012. result._maxZ = parsedMesh.maxZ;
  43013. result._width = parsedMesh.width;
  43014. result._height = parsedMesh.height;
  43015. return result;
  43016. };
  43017. return GroundMesh;
  43018. }(BABYLON.Mesh));
  43019. BABYLON.GroundMesh = GroundMesh;
  43020. })(BABYLON || (BABYLON = {}));
  43021. //# sourceMappingURL=babylon.groundMesh.js.map
  43022. var BABYLON;
  43023. (function (BABYLON) {
  43024. /**
  43025. * Creates an instance based on a source mesh.
  43026. */
  43027. var InstancedMesh = (function (_super) {
  43028. __extends(InstancedMesh, _super);
  43029. function InstancedMesh(name, source) {
  43030. var _this = _super.call(this, name, source.getScene()) || this;
  43031. source.instances.push(_this);
  43032. _this._sourceMesh = source;
  43033. _this.position.copyFrom(source.position);
  43034. _this.rotation.copyFrom(source.rotation);
  43035. _this.scaling.copyFrom(source.scaling);
  43036. if (source.rotationQuaternion) {
  43037. _this.rotationQuaternion = source.rotationQuaternion.clone();
  43038. }
  43039. _this.infiniteDistance = source.infiniteDistance;
  43040. _this.setPivotMatrix(source.getPivotMatrix());
  43041. _this.refreshBoundingInfo();
  43042. _this._syncSubMeshes();
  43043. return _this;
  43044. }
  43045. /**
  43046. * Returns the string "InstancedMesh".
  43047. */
  43048. InstancedMesh.prototype.getClassName = function () {
  43049. return "InstancedMesh";
  43050. };
  43051. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  43052. // Methods
  43053. get: function () {
  43054. return this._sourceMesh.receiveShadows;
  43055. },
  43056. enumerable: true,
  43057. configurable: true
  43058. });
  43059. Object.defineProperty(InstancedMesh.prototype, "material", {
  43060. get: function () {
  43061. return this._sourceMesh.material;
  43062. },
  43063. enumerable: true,
  43064. configurable: true
  43065. });
  43066. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  43067. get: function () {
  43068. return this._sourceMesh.visibility;
  43069. },
  43070. enumerable: true,
  43071. configurable: true
  43072. });
  43073. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  43074. get: function () {
  43075. return this._sourceMesh.skeleton;
  43076. },
  43077. enumerable: true,
  43078. configurable: true
  43079. });
  43080. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  43081. get: function () {
  43082. return this._sourceMesh.renderingGroupId;
  43083. },
  43084. enumerable: true,
  43085. configurable: true
  43086. });
  43087. /**
  43088. * Returns the total number of vertices (integer).
  43089. */
  43090. InstancedMesh.prototype.getTotalVertices = function () {
  43091. return this._sourceMesh.getTotalVertices();
  43092. };
  43093. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  43094. get: function () {
  43095. return this._sourceMesh;
  43096. },
  43097. enumerable: true,
  43098. configurable: true
  43099. });
  43100. /**
  43101. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  43102. */
  43103. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  43104. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  43105. };
  43106. /**
  43107. * Sets the vertex data of the mesh geometry for the requested `kind`.
  43108. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  43109. * The `data` are either a numeric array either a Float32Array.
  43110. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  43111. * 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).
  43112. * Note that a new underlying VertexBuffer object is created each call.
  43113. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  43114. *
  43115. * Possible `kind` values :
  43116. * - BABYLON.VertexBuffer.PositionKind
  43117. * - BABYLON.VertexBuffer.UVKind
  43118. * - BABYLON.VertexBuffer.UV2Kind
  43119. * - BABYLON.VertexBuffer.UV3Kind
  43120. * - BABYLON.VertexBuffer.UV4Kind
  43121. * - BABYLON.VertexBuffer.UV5Kind
  43122. * - BABYLON.VertexBuffer.UV6Kind
  43123. * - BABYLON.VertexBuffer.ColorKind
  43124. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43125. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43126. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43127. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43128. *
  43129. * Returns the Mesh.
  43130. */
  43131. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  43132. if (this.sourceMesh) {
  43133. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  43134. }
  43135. return this.sourceMesh;
  43136. };
  43137. /**
  43138. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  43139. * If the mesh has no geometry, it is simply returned as it is.
  43140. * The `data` are either a numeric array either a Float32Array.
  43141. * No new underlying VertexBuffer object is created.
  43142. * 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.
  43143. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  43144. *
  43145. * Possible `kind` values :
  43146. * - BABYLON.VertexBuffer.PositionKind
  43147. * - BABYLON.VertexBuffer.UVKind
  43148. * - BABYLON.VertexBuffer.UV2Kind
  43149. * - BABYLON.VertexBuffer.UV3Kind
  43150. * - BABYLON.VertexBuffer.UV4Kind
  43151. * - BABYLON.VertexBuffer.UV5Kind
  43152. * - BABYLON.VertexBuffer.UV6Kind
  43153. * - BABYLON.VertexBuffer.ColorKind
  43154. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43155. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43156. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43157. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43158. *
  43159. * Returns the Mesh.
  43160. */
  43161. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  43162. if (this.sourceMesh) {
  43163. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  43164. }
  43165. return this.sourceMesh;
  43166. };
  43167. /**
  43168. * Sets the mesh indices.
  43169. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  43170. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  43171. * This method creates a new index buffer each call.
  43172. * Returns the Mesh.
  43173. */
  43174. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  43175. if (this.sourceMesh) {
  43176. this.sourceMesh.setIndices(indices, totalVertices);
  43177. }
  43178. return this.sourceMesh;
  43179. };
  43180. /**
  43181. * Boolean : True if the mesh owns the requested kind of data.
  43182. */
  43183. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  43184. return this._sourceMesh.isVerticesDataPresent(kind);
  43185. };
  43186. /**
  43187. * Returns an array of indices (IndicesArray).
  43188. */
  43189. InstancedMesh.prototype.getIndices = function () {
  43190. return this._sourceMesh.getIndices();
  43191. };
  43192. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  43193. get: function () {
  43194. return this._sourceMesh._positions;
  43195. },
  43196. enumerable: true,
  43197. configurable: true
  43198. });
  43199. /**
  43200. * Sets a new updated BoundingInfo to the mesh.
  43201. * Returns the mesh.
  43202. */
  43203. InstancedMesh.prototype.refreshBoundingInfo = function () {
  43204. var meshBB = this._sourceMesh.getBoundingInfo();
  43205. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  43206. this._updateBoundingInfo();
  43207. return this;
  43208. };
  43209. InstancedMesh.prototype._preActivate = function () {
  43210. if (this._currentLOD) {
  43211. this._currentLOD._preActivate();
  43212. }
  43213. return this;
  43214. };
  43215. InstancedMesh.prototype._activate = function (renderId) {
  43216. if (this._currentLOD) {
  43217. this._currentLOD._registerInstanceForRenderId(this, renderId);
  43218. }
  43219. return this;
  43220. };
  43221. /**
  43222. * Returns the current associated LOD AbstractMesh.
  43223. */
  43224. InstancedMesh.prototype.getLOD = function (camera) {
  43225. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  43226. if (this._currentLOD === this.sourceMesh) {
  43227. return this;
  43228. }
  43229. return this._currentLOD;
  43230. };
  43231. InstancedMesh.prototype._syncSubMeshes = function () {
  43232. this.releaseSubMeshes();
  43233. if (this._sourceMesh.subMeshes) {
  43234. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  43235. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  43236. }
  43237. }
  43238. return this;
  43239. };
  43240. InstancedMesh.prototype._generatePointsArray = function () {
  43241. return this._sourceMesh._generatePointsArray();
  43242. };
  43243. /**
  43244. * Creates a new InstancedMesh from the current mesh.
  43245. * - name (string) : the cloned mesh name
  43246. * - newParent (optional Node) : the optional Node to parent the clone to.
  43247. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  43248. *
  43249. * Returns the clone.
  43250. */
  43251. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43252. var result = this._sourceMesh.createInstance(name);
  43253. // Deep copy
  43254. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  43255. // Bounding info
  43256. this.refreshBoundingInfo();
  43257. // Parent
  43258. if (newParent) {
  43259. result.parent = newParent;
  43260. }
  43261. if (!doNotCloneChildren) {
  43262. // Children
  43263. for (var index = 0; index < this.getScene().meshes.length; index++) {
  43264. var mesh = this.getScene().meshes[index];
  43265. if (mesh.parent === this) {
  43266. mesh.clone(mesh.name, result);
  43267. }
  43268. }
  43269. }
  43270. result.computeWorldMatrix(true);
  43271. return result;
  43272. };
  43273. /**
  43274. * Disposes the InstancedMesh.
  43275. * Returns nothing.
  43276. */
  43277. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  43278. // Remove from mesh
  43279. var index = this._sourceMesh.instances.indexOf(this);
  43280. this._sourceMesh.instances.splice(index, 1);
  43281. _super.prototype.dispose.call(this, doNotRecurse);
  43282. };
  43283. return InstancedMesh;
  43284. }(BABYLON.AbstractMesh));
  43285. BABYLON.InstancedMesh = InstancedMesh;
  43286. })(BABYLON || (BABYLON = {}));
  43287. //# sourceMappingURL=babylon.instancedMesh.js.map
  43288. /// <reference path="babylon.mesh.ts" />
  43289. var BABYLON;
  43290. (function (BABYLON) {
  43291. var LinesMesh = (function (_super) {
  43292. __extends(LinesMesh, _super);
  43293. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  43294. if (parent === void 0) { parent = null; }
  43295. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  43296. _this.useVertexColor = useVertexColor;
  43297. _this.color = new BABYLON.Color3(1, 1, 1);
  43298. _this.alpha = 1;
  43299. if (source) {
  43300. _this.color = source.color.clone();
  43301. _this.alpha = source.alpha;
  43302. _this.useVertexColor = source.useVertexColor;
  43303. }
  43304. _this._intersectionThreshold = 0.1;
  43305. var options = {
  43306. attributes: [BABYLON.VertexBuffer.PositionKind],
  43307. uniforms: ["world", "viewProjection"],
  43308. needAlphaBlending: false,
  43309. };
  43310. if (!useVertexColor) {
  43311. options.uniforms.push("color");
  43312. options.needAlphaBlending = true;
  43313. }
  43314. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  43315. return _this;
  43316. }
  43317. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  43318. /**
  43319. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43320. * This margin is expressed in world space coordinates, so its value may vary.
  43321. * Default value is 0.1
  43322. * @returns the intersection Threshold value.
  43323. */
  43324. get: function () {
  43325. return this._intersectionThreshold;
  43326. },
  43327. /**
  43328. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43329. * This margin is expressed in world space coordinates, so its value may vary.
  43330. * @param value the new threshold to apply
  43331. */
  43332. set: function (value) {
  43333. if (this._intersectionThreshold === value) {
  43334. return;
  43335. }
  43336. this._intersectionThreshold = value;
  43337. if (this.geometry) {
  43338. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  43339. }
  43340. },
  43341. enumerable: true,
  43342. configurable: true
  43343. });
  43344. /**
  43345. * Returns the string "LineMesh"
  43346. */
  43347. LinesMesh.prototype.getClassName = function () {
  43348. return "LinesMesh";
  43349. };
  43350. Object.defineProperty(LinesMesh.prototype, "material", {
  43351. get: function () {
  43352. return this._colorShader;
  43353. },
  43354. enumerable: true,
  43355. configurable: true
  43356. });
  43357. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  43358. get: function () {
  43359. return false;
  43360. },
  43361. enumerable: true,
  43362. configurable: true
  43363. });
  43364. LinesMesh.prototype.createInstance = function (name) {
  43365. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  43366. return null;
  43367. };
  43368. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  43369. // VBOs
  43370. this._geometry._bind(this._colorShader.getEffect());
  43371. // Color
  43372. if (!this.useVertexColor) {
  43373. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  43374. }
  43375. return this;
  43376. };
  43377. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  43378. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  43379. return this;
  43380. }
  43381. var engine = this.getScene().getEngine();
  43382. // Draw order
  43383. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  43384. return this;
  43385. };
  43386. LinesMesh.prototype.dispose = function (doNotRecurse) {
  43387. this._colorShader.dispose();
  43388. _super.prototype.dispose.call(this, doNotRecurse);
  43389. };
  43390. /**
  43391. * Returns a new LineMesh object cloned from the current one.
  43392. */
  43393. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43394. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  43395. };
  43396. return LinesMesh;
  43397. }(BABYLON.Mesh));
  43398. BABYLON.LinesMesh = LinesMesh;
  43399. })(BABYLON || (BABYLON = {}));
  43400. //# sourceMappingURL=babylon.linesMesh.js.map
  43401. var BABYLON;
  43402. (function (BABYLON) {
  43403. var ShaderMaterial = (function (_super) {
  43404. __extends(ShaderMaterial, _super);
  43405. function ShaderMaterial(name, scene, shaderPath, options) {
  43406. var _this = _super.call(this, name, scene) || this;
  43407. _this._textures = {};
  43408. _this._textureArrays = {};
  43409. _this._floats = {};
  43410. _this._floatsArrays = {};
  43411. _this._colors3 = {};
  43412. _this._colors3Arrays = {};
  43413. _this._colors4 = {};
  43414. _this._vectors2 = {};
  43415. _this._vectors3 = {};
  43416. _this._vectors4 = {};
  43417. _this._matrices = {};
  43418. _this._matrices3x3 = {};
  43419. _this._matrices2x2 = {};
  43420. _this._vectors3Arrays = {};
  43421. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  43422. _this._shaderPath = shaderPath;
  43423. options.needAlphaBlending = options.needAlphaBlending || false;
  43424. options.needAlphaTesting = options.needAlphaTesting || false;
  43425. options.attributes = options.attributes || ["position", "normal", "uv"];
  43426. options.uniforms = options.uniforms || ["worldViewProjection"];
  43427. options.uniformBuffers = options.uniformBuffers || [];
  43428. options.samplers = options.samplers || [];
  43429. options.defines = options.defines || [];
  43430. _this._options = options;
  43431. return _this;
  43432. }
  43433. ShaderMaterial.prototype.getClassName = function () {
  43434. return "ShaderMaterial";
  43435. };
  43436. ShaderMaterial.prototype.needAlphaBlending = function () {
  43437. return this._options.needAlphaBlending;
  43438. };
  43439. ShaderMaterial.prototype.needAlphaTesting = function () {
  43440. return this._options.needAlphaTesting;
  43441. };
  43442. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  43443. if (this._options.uniforms.indexOf(uniformName) === -1) {
  43444. this._options.uniforms.push(uniformName);
  43445. }
  43446. };
  43447. ShaderMaterial.prototype.setTexture = function (name, texture) {
  43448. if (this._options.samplers.indexOf(name) === -1) {
  43449. this._options.samplers.push(name);
  43450. }
  43451. this._textures[name] = texture;
  43452. return this;
  43453. };
  43454. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  43455. if (this._options.samplers.indexOf(name) === -1) {
  43456. this._options.samplers.push(name);
  43457. }
  43458. this._checkUniform(name);
  43459. this._textureArrays[name] = textures;
  43460. return this;
  43461. };
  43462. ShaderMaterial.prototype.setFloat = function (name, value) {
  43463. this._checkUniform(name);
  43464. this._floats[name] = value;
  43465. return this;
  43466. };
  43467. ShaderMaterial.prototype.setFloats = function (name, value) {
  43468. this._checkUniform(name);
  43469. this._floatsArrays[name] = value;
  43470. return this;
  43471. };
  43472. ShaderMaterial.prototype.setColor3 = function (name, value) {
  43473. this._checkUniform(name);
  43474. this._colors3[name] = value;
  43475. return this;
  43476. };
  43477. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  43478. this._checkUniform(name);
  43479. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  43480. color.toArray(arr, arr.length);
  43481. return arr;
  43482. }, []);
  43483. return this;
  43484. };
  43485. ShaderMaterial.prototype.setColor4 = function (name, value) {
  43486. this._checkUniform(name);
  43487. this._colors4[name] = value;
  43488. return this;
  43489. };
  43490. ShaderMaterial.prototype.setVector2 = function (name, value) {
  43491. this._checkUniform(name);
  43492. this._vectors2[name] = value;
  43493. return this;
  43494. };
  43495. ShaderMaterial.prototype.setVector3 = function (name, value) {
  43496. this._checkUniform(name);
  43497. this._vectors3[name] = value;
  43498. return this;
  43499. };
  43500. ShaderMaterial.prototype.setVector4 = function (name, value) {
  43501. this._checkUniform(name);
  43502. this._vectors4[name] = value;
  43503. return this;
  43504. };
  43505. ShaderMaterial.prototype.setMatrix = function (name, value) {
  43506. this._checkUniform(name);
  43507. this._matrices[name] = value;
  43508. return this;
  43509. };
  43510. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  43511. this._checkUniform(name);
  43512. this._matrices3x3[name] = value;
  43513. return this;
  43514. };
  43515. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  43516. this._checkUniform(name);
  43517. this._matrices2x2[name] = value;
  43518. return this;
  43519. };
  43520. ShaderMaterial.prototype.setArray3 = function (name, value) {
  43521. this._checkUniform(name);
  43522. this._vectors3Arrays[name] = value;
  43523. return this;
  43524. };
  43525. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  43526. if (!mesh) {
  43527. return true;
  43528. }
  43529. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  43530. return false;
  43531. }
  43532. return false;
  43533. };
  43534. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  43535. var scene = this.getScene();
  43536. var engine = scene.getEngine();
  43537. if (!this.checkReadyOnEveryCall) {
  43538. if (this._renderId === scene.getRenderId()) {
  43539. if (this._checkCache(scene, mesh, useInstances)) {
  43540. return true;
  43541. }
  43542. }
  43543. }
  43544. // Instances
  43545. var defines = [];
  43546. var attribs = [];
  43547. var fallbacks = new BABYLON.EffectFallbacks();
  43548. if (useInstances) {
  43549. defines.push("#define INSTANCES");
  43550. }
  43551. for (var index = 0; index < this._options.defines.length; index++) {
  43552. defines.push(this._options.defines[index]);
  43553. }
  43554. for (var index = 0; index < this._options.attributes.length; index++) {
  43555. attribs.push(this._options.attributes[index]);
  43556. }
  43557. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  43558. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43559. defines.push("#define VERTEXCOLOR");
  43560. }
  43561. // Bones
  43562. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  43563. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43564. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43565. if (mesh.numBoneInfluencers > 4) {
  43566. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43567. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43568. }
  43569. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43570. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43571. fallbacks.addCPUSkinningFallback(0, mesh);
  43572. if (this._options.uniforms.indexOf("mBones") === -1) {
  43573. this._options.uniforms.push("mBones");
  43574. }
  43575. }
  43576. else {
  43577. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43578. }
  43579. // Textures
  43580. for (var name in this._textures) {
  43581. if (!this._textures[name].isReady()) {
  43582. return false;
  43583. }
  43584. }
  43585. // Alpha test
  43586. if (engine.getAlphaTesting()) {
  43587. defines.push("#define ALPHATEST");
  43588. }
  43589. var previousEffect = this._effect;
  43590. var join = defines.join("\n");
  43591. this._effect = engine.createEffect(this._shaderPath, {
  43592. attributes: attribs,
  43593. uniformsNames: this._options.uniforms,
  43594. uniformBuffersNames: this._options.uniformBuffers,
  43595. samplers: this._options.samplers,
  43596. defines: join,
  43597. fallbacks: fallbacks,
  43598. onCompiled: this.onCompiled,
  43599. onError: this.onError
  43600. }, engine);
  43601. if (!this._effect.isReady()) {
  43602. return false;
  43603. }
  43604. if (previousEffect !== this._effect) {
  43605. scene.resetCachedMaterial();
  43606. }
  43607. this._renderId = scene.getRenderId();
  43608. return true;
  43609. };
  43610. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43611. var scene = this.getScene();
  43612. if (this._options.uniforms.indexOf("world") !== -1) {
  43613. this._effect.setMatrix("world", world);
  43614. }
  43615. if (this._options.uniforms.indexOf("worldView") !== -1) {
  43616. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  43617. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  43618. }
  43619. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  43620. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  43621. }
  43622. };
  43623. ShaderMaterial.prototype.bind = function (world, mesh) {
  43624. // Std values
  43625. this.bindOnlyWorldMatrix(world);
  43626. if (this.getScene().getCachedMaterial() !== this) {
  43627. if (this._options.uniforms.indexOf("view") !== -1) {
  43628. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  43629. }
  43630. if (this._options.uniforms.indexOf("projection") !== -1) {
  43631. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  43632. }
  43633. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  43634. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  43635. }
  43636. // Bones
  43637. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  43638. var name;
  43639. // Texture
  43640. for (name in this._textures) {
  43641. this._effect.setTexture(name, this._textures[name]);
  43642. }
  43643. // Texture arrays
  43644. for (name in this._textureArrays) {
  43645. this._effect.setTextureArray(name, this._textureArrays[name]);
  43646. }
  43647. // Float
  43648. for (name in this._floats) {
  43649. this._effect.setFloat(name, this._floats[name]);
  43650. }
  43651. // Float s
  43652. for (name in this._floatsArrays) {
  43653. this._effect.setArray(name, this._floatsArrays[name]);
  43654. }
  43655. // Color3
  43656. for (name in this._colors3) {
  43657. this._effect.setColor3(name, this._colors3[name]);
  43658. }
  43659. for (name in this._colors3Arrays) {
  43660. this._effect.setArray3(name, this._colors3Arrays[name]);
  43661. }
  43662. // Color4
  43663. for (name in this._colors4) {
  43664. var color = this._colors4[name];
  43665. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  43666. }
  43667. // Vector2
  43668. for (name in this._vectors2) {
  43669. this._effect.setVector2(name, this._vectors2[name]);
  43670. }
  43671. // Vector3
  43672. for (name in this._vectors3) {
  43673. this._effect.setVector3(name, this._vectors3[name]);
  43674. }
  43675. // Vector4
  43676. for (name in this._vectors4) {
  43677. this._effect.setVector4(name, this._vectors4[name]);
  43678. }
  43679. // Matrix
  43680. for (name in this._matrices) {
  43681. this._effect.setMatrix(name, this._matrices[name]);
  43682. }
  43683. // Matrix 3x3
  43684. for (name in this._matrices3x3) {
  43685. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  43686. }
  43687. // Matrix 2x2
  43688. for (name in this._matrices2x2) {
  43689. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  43690. }
  43691. // Vector3Array
  43692. for (name in this._vectors3Arrays) {
  43693. this._effect.setArray3(name, this._vectors3Arrays[name]);
  43694. }
  43695. }
  43696. this._afterBind(mesh);
  43697. };
  43698. ShaderMaterial.prototype.getActiveTextures = function () {
  43699. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43700. for (var name in this._textures) {
  43701. activeTextures.push(this._textures[name]);
  43702. }
  43703. for (var name in this._textureArrays) {
  43704. var array = this._textureArrays[name];
  43705. for (var index = 0; index < array.length; index++) {
  43706. activeTextures.push(array[index]);
  43707. }
  43708. }
  43709. return activeTextures;
  43710. };
  43711. ShaderMaterial.prototype.hasTexture = function (texture) {
  43712. if (_super.prototype.hasTexture.call(this, texture)) {
  43713. return true;
  43714. }
  43715. for (var name in this._textures) {
  43716. if (this._textures[name] === texture) {
  43717. return true;
  43718. }
  43719. }
  43720. for (var name in this._textureArrays) {
  43721. var array = this._textureArrays[name];
  43722. for (var index = 0; index < array.length; index++) {
  43723. if (array[index] === texture) {
  43724. return true;
  43725. }
  43726. }
  43727. }
  43728. return false;
  43729. };
  43730. ShaderMaterial.prototype.clone = function (name) {
  43731. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  43732. return newShaderMaterial;
  43733. };
  43734. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43735. if (forceDisposeTextures) {
  43736. var name;
  43737. for (name in this._textures) {
  43738. this._textures[name].dispose();
  43739. }
  43740. for (name in this._textureArrays) {
  43741. var array = this._textureArrays[name];
  43742. for (var index = 0; index < array.length; index++) {
  43743. array[index].dispose();
  43744. }
  43745. }
  43746. }
  43747. this._textures = {};
  43748. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43749. };
  43750. ShaderMaterial.prototype.serialize = function () {
  43751. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43752. serializationObject.customType = "BABYLON.ShaderMaterial";
  43753. serializationObject.options = this._options;
  43754. serializationObject.shaderPath = this._shaderPath;
  43755. var name;
  43756. // Texture
  43757. serializationObject.textures = {};
  43758. for (name in this._textures) {
  43759. serializationObject.textures[name] = this._textures[name].serialize();
  43760. }
  43761. // Texture arrays
  43762. serializationObject.textureArrays = {};
  43763. for (name in this._textureArrays) {
  43764. serializationObject.textureArrays[name] = [];
  43765. var array = this._textureArrays[name];
  43766. for (var index = 0; index < array.length; index++) {
  43767. serializationObject.textureArrays[name].push(array[index].serialize());
  43768. }
  43769. }
  43770. // Float
  43771. serializationObject.floats = {};
  43772. for (name in this._floats) {
  43773. serializationObject.floats[name] = this._floats[name];
  43774. }
  43775. // Float s
  43776. serializationObject.floatArrays = {};
  43777. for (name in this._floatsArrays) {
  43778. serializationObject.floatArrays[name] = this._floatsArrays[name];
  43779. }
  43780. // Color3
  43781. serializationObject.colors3 = {};
  43782. for (name in this._colors3) {
  43783. serializationObject.colors3[name] = this._colors3[name].asArray();
  43784. }
  43785. // Color3 array
  43786. serializationObject.colors3Arrays = {};
  43787. for (name in this._colors3Arrays) {
  43788. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  43789. }
  43790. // Color4
  43791. serializationObject.colors4 = {};
  43792. for (name in this._colors4) {
  43793. serializationObject.colors4[name] = this._colors4[name].asArray();
  43794. }
  43795. // Vector2
  43796. serializationObject.vectors2 = {};
  43797. for (name in this._vectors2) {
  43798. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  43799. }
  43800. // Vector3
  43801. serializationObject.vectors3 = {};
  43802. for (name in this._vectors3) {
  43803. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  43804. }
  43805. // Vector4
  43806. serializationObject.vectors4 = {};
  43807. for (name in this._vectors4) {
  43808. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  43809. }
  43810. // Matrix
  43811. serializationObject.matrices = {};
  43812. for (name in this._matrices) {
  43813. serializationObject.matrices[name] = this._matrices[name].asArray();
  43814. }
  43815. // Matrix 3x3
  43816. serializationObject.matrices3x3 = {};
  43817. for (name in this._matrices3x3) {
  43818. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  43819. }
  43820. // Matrix 2x2
  43821. serializationObject.matrices2x2 = {};
  43822. for (name in this._matrices2x2) {
  43823. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  43824. }
  43825. // Vector3Array
  43826. serializationObject.vectors3Arrays = {};
  43827. for (name in this._vectors3Arrays) {
  43828. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  43829. }
  43830. return serializationObject;
  43831. };
  43832. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  43833. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  43834. var name;
  43835. // Texture
  43836. for (name in source.textures) {
  43837. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  43838. }
  43839. // Texture arrays
  43840. for (name in source.textureArrays) {
  43841. var array = source.textureArrays[name];
  43842. var textureArray = new Array();
  43843. for (var index = 0; index < array.length; index++) {
  43844. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  43845. }
  43846. material.setTextureArray(name, textureArray);
  43847. }
  43848. // Float
  43849. for (name in source.floats) {
  43850. material.setFloat(name, source.floats[name]);
  43851. }
  43852. // Float s
  43853. for (name in source.floatsArrays) {
  43854. material.setFloats(name, source.floatsArrays[name]);
  43855. }
  43856. // Color3
  43857. for (name in source.colors3) {
  43858. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  43859. }
  43860. // Color3 arrays
  43861. for (name in source.colors3Arrays) {
  43862. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  43863. if (i % 3 === 0) {
  43864. arr.push([num]);
  43865. }
  43866. else {
  43867. arr[arr.length - 1].push(num);
  43868. }
  43869. return arr;
  43870. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  43871. material.setColor3Array(name, colors);
  43872. }
  43873. // Color4
  43874. for (name in source.colors4) {
  43875. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  43876. }
  43877. // Vector2
  43878. for (name in source.vectors2) {
  43879. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  43880. }
  43881. // Vector3
  43882. for (name in source.vectors3) {
  43883. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  43884. }
  43885. // Vector4
  43886. for (name in source.vectors4) {
  43887. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  43888. }
  43889. // Matrix
  43890. for (name in source.matrices) {
  43891. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  43892. }
  43893. // Matrix 3x3
  43894. for (name in source.matrices3x3) {
  43895. material.setMatrix3x3(name, source.matrices3x3[name]);
  43896. }
  43897. // Matrix 2x2
  43898. for (name in source.matrices2x2) {
  43899. material.setMatrix2x2(name, source.matrices2x2[name]);
  43900. }
  43901. // Vector3Array
  43902. for (name in source.vectors3Arrays) {
  43903. material.setArray3(name, source.vectors3Arrays[name]);
  43904. }
  43905. return material;
  43906. };
  43907. return ShaderMaterial;
  43908. }(BABYLON.Material));
  43909. BABYLON.ShaderMaterial = ShaderMaterial;
  43910. })(BABYLON || (BABYLON = {}));
  43911. //# sourceMappingURL=babylon.shaderMaterial.js.map
  43912. var BABYLON;
  43913. (function (BABYLON) {
  43914. var MeshBuilder = (function () {
  43915. function MeshBuilder() {
  43916. }
  43917. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  43918. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  43919. return BABYLON.Mesh.DOUBLESIDE;
  43920. }
  43921. if (orientation === undefined || orientation === null) {
  43922. return BABYLON.Mesh.FRONTSIDE;
  43923. }
  43924. return orientation;
  43925. };
  43926. /**
  43927. * Creates a box mesh.
  43928. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  43929. * The parameter `size` sets the size (float) of each box side (default 1).
  43930. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  43931. * 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).
  43932. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  43933. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43934. * 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).
  43935. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43936. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43937. */
  43938. MeshBuilder.CreateBox = function (name, options, scene) {
  43939. var box = new BABYLON.Mesh(name, scene);
  43940. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43941. box._originalBuilderSideOrientation = options.sideOrientation;
  43942. var vertexData = BABYLON.VertexData.CreateBox(options);
  43943. vertexData.applyToMesh(box, options.updatable);
  43944. return box;
  43945. };
  43946. /**
  43947. * Creates a sphere mesh.
  43948. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  43949. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  43950. * 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`).
  43951. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  43952. * 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
  43953. * 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).
  43954. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43955. * 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).
  43956. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43957. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43958. */
  43959. MeshBuilder.CreateSphere = function (name, options, scene) {
  43960. var sphere = new BABYLON.Mesh(name, scene);
  43961. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43962. sphere._originalBuilderSideOrientation = options.sideOrientation;
  43963. var vertexData = BABYLON.VertexData.CreateSphere(options);
  43964. vertexData.applyToMesh(sphere, options.updatable);
  43965. return sphere;
  43966. };
  43967. /**
  43968. * Creates a plane polygonal mesh. By default, this is a disc.
  43969. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  43970. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  43971. * 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.
  43972. * 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
  43973. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43974. * 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).
  43975. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43976. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43977. */
  43978. MeshBuilder.CreateDisc = function (name, options, scene) {
  43979. var disc = new BABYLON.Mesh(name, scene);
  43980. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43981. disc._originalBuilderSideOrientation = options.sideOrientation;
  43982. var vertexData = BABYLON.VertexData.CreateDisc(options);
  43983. vertexData.applyToMesh(disc, options.updatable);
  43984. return disc;
  43985. };
  43986. /**
  43987. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  43988. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  43989. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  43990. * 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`).
  43991. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  43992. * 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.
  43993. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43994. * 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).
  43995. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43996. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43997. */
  43998. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  43999. var sphere = new BABYLON.Mesh(name, scene);
  44000. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44001. sphere._originalBuilderSideOrientation = options.sideOrientation;
  44002. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  44003. vertexData.applyToMesh(sphere, options.updatable);
  44004. return sphere;
  44005. };
  44006. ;
  44007. /**
  44008. * Creates a ribbon mesh.
  44009. * 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.
  44010. *
  44011. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  44012. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  44013. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  44014. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  44015. * 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.
  44016. * 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.
  44017. * 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
  44018. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44019. * 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).
  44020. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44021. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44022. * 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.
  44023. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  44024. * 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
  44025. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  44026. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  44027. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44028. */
  44029. MeshBuilder.CreateRibbon = function (name, options, scene) {
  44030. var pathArray = options.pathArray;
  44031. var closeArray = options.closeArray;
  44032. var closePath = options.closePath;
  44033. var offset = options.offset;
  44034. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44035. var instance = options.instance;
  44036. var updatable = options.updatable;
  44037. if (instance) {
  44038. // positionFunction : ribbon case
  44039. // only pathArray and sideOrientation parameters are taken into account for positions update
  44040. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  44041. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  44042. var positionFunction = function (positions) {
  44043. var minlg = pathArray[0].length;
  44044. var i = 0;
  44045. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  44046. for (var si = 1; si <= ns; si++) {
  44047. for (var p = 0; p < pathArray.length; p++) {
  44048. var path = pathArray[p];
  44049. var l = path.length;
  44050. minlg = (minlg < l) ? minlg : l;
  44051. var j = 0;
  44052. while (j < minlg) {
  44053. positions[i] = path[j].x;
  44054. positions[i + 1] = path[j].y;
  44055. positions[i + 2] = path[j].z;
  44056. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  44057. BABYLON.Tmp.Vector3[0].x = path[j].x;
  44058. }
  44059. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  44060. BABYLON.Tmp.Vector3[1].x = path[j].x;
  44061. }
  44062. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  44063. BABYLON.Tmp.Vector3[0].y = path[j].y;
  44064. }
  44065. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  44066. BABYLON.Tmp.Vector3[1].y = path[j].y;
  44067. }
  44068. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  44069. BABYLON.Tmp.Vector3[0].z = path[j].z;
  44070. }
  44071. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  44072. BABYLON.Tmp.Vector3[1].z = path[j].z;
  44073. }
  44074. j++;
  44075. i += 3;
  44076. }
  44077. if (instance._closePath) {
  44078. positions[i] = path[0].x;
  44079. positions[i + 1] = path[0].y;
  44080. positions[i + 2] = path[0].z;
  44081. i += 3;
  44082. }
  44083. }
  44084. }
  44085. };
  44086. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44087. positionFunction(positions);
  44088. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  44089. instance._boundingInfo.update(instance._worldMatrix);
  44090. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  44091. if (options.colors) {
  44092. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44093. for (var c = 0; c < options.colors.length; c++) {
  44094. colors[c * 4] = options.colors[c].r;
  44095. colors[c * 4 + 1] = options.colors[c].g;
  44096. colors[c * 4 + 2] = options.colors[c].b;
  44097. colors[c * 4 + 3] = options.colors[c].a;
  44098. }
  44099. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  44100. }
  44101. if (options.uvs) {
  44102. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44103. for (var i = 0; i < options.uvs.length; i++) {
  44104. uvs[i * 2] = options.uvs[i].x;
  44105. uvs[i * 2 + 1] = options.uvs[i].y;
  44106. }
  44107. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  44108. }
  44109. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  44110. var indices = instance.getIndices();
  44111. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44112. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  44113. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  44114. if (instance._closePath) {
  44115. var indexFirst = 0;
  44116. var indexLast = 0;
  44117. for (var p = 0; p < pathArray.length; p++) {
  44118. indexFirst = instance._idx[p] * 3;
  44119. if (p + 1 < pathArray.length) {
  44120. indexLast = (instance._idx[p + 1] - 1) * 3;
  44121. }
  44122. else {
  44123. indexLast = normals.length - 3;
  44124. }
  44125. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  44126. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  44127. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  44128. normals[indexLast] = normals[indexFirst];
  44129. normals[indexLast + 1] = normals[indexFirst + 1];
  44130. normals[indexLast + 2] = normals[indexFirst + 2];
  44131. }
  44132. }
  44133. if (!(instance.areNormalsFrozen)) {
  44134. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  44135. }
  44136. }
  44137. return instance;
  44138. }
  44139. else {
  44140. var ribbon = new BABYLON.Mesh(name, scene);
  44141. ribbon._originalBuilderSideOrientation = sideOrientation;
  44142. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  44143. if (closePath) {
  44144. ribbon._idx = vertexData._idx;
  44145. }
  44146. ribbon._closePath = closePath;
  44147. ribbon._closeArray = closeArray;
  44148. vertexData.applyToMesh(ribbon, updatable);
  44149. return ribbon;
  44150. }
  44151. };
  44152. /**
  44153. * Creates a cylinder or a cone mesh.
  44154. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  44155. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  44156. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  44157. * 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.
  44158. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  44159. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  44160. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  44161. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  44162. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  44163. * 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).
  44164. * 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
  44165. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  44166. * 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
  44167. * 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.
  44168. * If `enclose` is false, a ring surface is one element.
  44169. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  44170. * 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
  44171. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44172. * 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).
  44173. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44175. */
  44176. MeshBuilder.CreateCylinder = function (name, options, scene) {
  44177. var cylinder = new BABYLON.Mesh(name, scene);
  44178. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44179. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  44180. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  44181. vertexData.applyToMesh(cylinder, options.updatable);
  44182. return cylinder;
  44183. };
  44184. /**
  44185. * Creates a torus mesh.
  44186. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  44187. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  44188. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  44189. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  44190. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44191. * 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).
  44192. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44193. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44194. */
  44195. MeshBuilder.CreateTorus = function (name, options, scene) {
  44196. var torus = new BABYLON.Mesh(name, scene);
  44197. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44198. torus._originalBuilderSideOrientation = options.sideOrientation;
  44199. var vertexData = BABYLON.VertexData.CreateTorus(options);
  44200. vertexData.applyToMesh(torus, options.updatable);
  44201. return torus;
  44202. };
  44203. /**
  44204. * Creates a torus knot mesh.
  44205. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  44206. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  44207. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  44208. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  44209. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  44210. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44211. * 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).
  44212. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44213. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44214. */
  44215. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  44216. var torusKnot = new BABYLON.Mesh(name, scene);
  44217. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44218. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  44219. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  44220. vertexData.applyToMesh(torusKnot, options.updatable);
  44221. return torusKnot;
  44222. };
  44223. /**
  44224. * Creates a line system mesh.
  44225. * A line system is a pool of many lines gathered in a single mesh.
  44226. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  44227. * 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.
  44228. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  44229. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  44230. * 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
  44231. * 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
  44232. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  44233. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44234. */
  44235. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  44236. var instance = options.instance;
  44237. var lines = options.lines;
  44238. if (instance) {
  44239. var positionFunction = function (positions) {
  44240. var i = 0;
  44241. for (var l = 0; l < lines.length; l++) {
  44242. var points = lines[l];
  44243. for (var p = 0; p < points.length; p++) {
  44244. positions[i] = points[p].x;
  44245. positions[i + 1] = points[p].y;
  44246. positions[i + 2] = points[p].z;
  44247. i += 3;
  44248. }
  44249. }
  44250. };
  44251. instance.updateMeshPositions(positionFunction, false);
  44252. return instance;
  44253. }
  44254. // line system creation
  44255. var lineSystem = new BABYLON.LinesMesh(name, scene);
  44256. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  44257. vertexData.applyToMesh(lineSystem, options.updatable);
  44258. return lineSystem;
  44259. };
  44260. /**
  44261. * Creates a line mesh.
  44262. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  44263. * 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.
  44264. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  44265. * The parameter `points` is an array successive Vector3.
  44266. * 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
  44267. * When updating an instance, remember that only point positions can change, not the number of points.
  44268. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44269. */
  44270. MeshBuilder.CreateLines = function (name, options, scene) {
  44271. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  44272. return lines;
  44273. };
  44274. /**
  44275. * Creates a dashed line mesh.
  44276. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  44277. * 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.
  44278. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  44279. * The parameter `points` is an array successive Vector3.
  44280. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  44281. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  44282. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  44283. * 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
  44284. * When updating an instance, remember that only point positions can change, not the number of points.
  44285. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44286. */
  44287. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  44288. var points = options.points;
  44289. var instance = options.instance;
  44290. var gapSize = options.gapSize || 1;
  44291. var dashSize = options.dashSize || 3;
  44292. if (instance) {
  44293. var positionFunction = function (positions) {
  44294. var curvect = BABYLON.Vector3.Zero();
  44295. var nbSeg = positions.length / 6;
  44296. var lg = 0;
  44297. var nb = 0;
  44298. var shft = 0;
  44299. var dashshft = 0;
  44300. var curshft = 0;
  44301. var p = 0;
  44302. var i = 0;
  44303. var j = 0;
  44304. for (i = 0; i < points.length - 1; i++) {
  44305. points[i + 1].subtractToRef(points[i], curvect);
  44306. lg += curvect.length();
  44307. }
  44308. shft = lg / nbSeg;
  44309. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  44310. for (i = 0; i < points.length - 1; i++) {
  44311. points[i + 1].subtractToRef(points[i], curvect);
  44312. nb = Math.floor(curvect.length() / shft);
  44313. curvect.normalize();
  44314. j = 0;
  44315. while (j < nb && p < positions.length) {
  44316. curshft = shft * j;
  44317. positions[p] = points[i].x + curshft * curvect.x;
  44318. positions[p + 1] = points[i].y + curshft * curvect.y;
  44319. positions[p + 2] = points[i].z + curshft * curvect.z;
  44320. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  44321. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  44322. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  44323. p += 6;
  44324. j++;
  44325. }
  44326. }
  44327. while (p < positions.length) {
  44328. positions[p] = points[i].x;
  44329. positions[p + 1] = points[i].y;
  44330. positions[p + 2] = points[i].z;
  44331. p += 3;
  44332. }
  44333. };
  44334. instance.updateMeshPositions(positionFunction, false);
  44335. return instance;
  44336. }
  44337. // dashed lines creation
  44338. var dashedLines = new BABYLON.LinesMesh(name, scene);
  44339. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  44340. vertexData.applyToMesh(dashedLines, options.updatable);
  44341. dashedLines.dashSize = dashSize;
  44342. dashedLines.gapSize = gapSize;
  44343. return dashedLines;
  44344. };
  44345. /**
  44346. * Creates an extruded shape mesh.
  44347. * 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.
  44348. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  44349. *
  44350. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  44351. * 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
  44352. * extruded along the Z axis.
  44353. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  44354. * 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.
  44355. * The parameter `scale` (float, default 1) is the value to scale the shape.
  44356. * 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
  44357. * 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
  44358. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  44359. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44360. * 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).
  44361. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44362. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44363. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44364. */
  44365. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  44366. var path = options.path;
  44367. var shape = options.shape;
  44368. var scale = options.scale || 1;
  44369. var rotation = options.rotation || 0;
  44370. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  44371. var updatable = options.updatable;
  44372. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44373. var instance = options.instance;
  44374. var invertUV = options.invertUV || false;
  44375. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  44376. };
  44377. /**
  44378. * Creates an custom extruded shape mesh.
  44379. * 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.
  44380. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  44381. *
  44382. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  44383. * 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
  44384. * extruded along the Z axis.
  44385. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  44386. * 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
  44387. * and the distance of this point from the begining of the path :
  44388. * ```javascript
  44389. * var rotationFunction = function(i, distance) {
  44390. * // do things
  44391. * return rotationValue; }
  44392. * ```
  44393. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  44394. * 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
  44395. * and the distance of this point from the begining of the path :
  44396. * ```javascript
  44397. * var scaleFunction = function(i, distance) {
  44398. * // do things
  44399. * return scaleValue;}
  44400. * ```
  44401. * It must returns a float value that will be the scale value applied to the shape on each path point.
  44402. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  44403. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  44404. * 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
  44405. * 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
  44406. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  44407. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44408. * 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).
  44409. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44410. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44411. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44412. */
  44413. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  44414. var path = options.path;
  44415. var shape = options.shape;
  44416. var scaleFunction = options.scaleFunction || (function () { return 1; });
  44417. var rotationFunction = options.rotationFunction || (function () { return 0; });
  44418. var ribbonCloseArray = options.ribbonCloseArray || false;
  44419. var ribbonClosePath = options.ribbonClosePath || false;
  44420. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  44421. var updatable = options.updatable;
  44422. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44423. var instance = options.instance;
  44424. var invertUV = options.invertUV || false;
  44425. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  44426. };
  44427. /**
  44428. * Creates lathe mesh.
  44429. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  44430. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  44431. *
  44432. * 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
  44433. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  44434. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  44435. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  44436. * 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.
  44437. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  44438. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  44439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44440. * 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).
  44441. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44442. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44443. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44444. */
  44445. MeshBuilder.CreateLathe = function (name, options, scene) {
  44446. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  44447. var closed = (options.closed === undefined) ? true : options.closed;
  44448. var shape = options.shape;
  44449. var radius = options.radius || 1;
  44450. var tessellation = options.tessellation || 64;
  44451. var updatable = options.updatable;
  44452. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44453. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  44454. var pi2 = Math.PI * 2;
  44455. var paths = new Array();
  44456. var invertUV = options.invertUV || false;
  44457. var i = 0;
  44458. var p = 0;
  44459. var step = pi2 / tessellation * arc;
  44460. var rotated;
  44461. var path = new Array();
  44462. ;
  44463. for (i = 0; i <= tessellation; i++) {
  44464. var path = [];
  44465. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  44466. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  44467. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  44468. }
  44469. for (p = 0; p < shape.length; p++) {
  44470. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  44471. path.push(rotated);
  44472. }
  44473. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  44474. 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));
  44475. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  44476. }
  44477. paths.push(path);
  44478. }
  44479. // lathe ribbon
  44480. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  44481. return lathe;
  44482. };
  44483. /**
  44484. * Creates a plane mesh.
  44485. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  44486. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  44487. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  44488. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  44489. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44490. * 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).
  44491. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44492. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44493. */
  44494. MeshBuilder.CreatePlane = function (name, options, scene) {
  44495. var plane = new BABYLON.Mesh(name, scene);
  44496. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44497. plane._originalBuilderSideOrientation = options.sideOrientation;
  44498. var vertexData = BABYLON.VertexData.CreatePlane(options);
  44499. vertexData.applyToMesh(plane, options.updatable);
  44500. if (options.sourcePlane) {
  44501. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  44502. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  44503. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  44504. plane.rotate(vectorProduct, product);
  44505. }
  44506. return plane;
  44507. };
  44508. /**
  44509. * Creates a ground mesh.
  44510. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  44511. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  44512. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  44513. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44514. */
  44515. MeshBuilder.CreateGround = function (name, options, scene) {
  44516. var ground = new BABYLON.GroundMesh(name, scene);
  44517. ground._setReady(false);
  44518. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  44519. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  44520. ground._width = options.width || 1;
  44521. ground._height = options.height || 1;
  44522. ground._maxX = ground._width / 2;
  44523. ground._maxZ = ground._height / 2;
  44524. ground._minX = -ground._maxX;
  44525. ground._minZ = -ground._maxZ;
  44526. var vertexData = BABYLON.VertexData.CreateGround(options);
  44527. vertexData.applyToMesh(ground, options.updatable);
  44528. ground._setReady(true);
  44529. return ground;
  44530. };
  44531. /**
  44532. * Creates a tiled ground mesh.
  44533. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  44534. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  44535. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  44536. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  44537. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  44538. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  44539. * numbers of subdivisions on the ground width and height of each tile.
  44540. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44541. */
  44542. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  44543. var tiledGround = new BABYLON.Mesh(name, scene);
  44544. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  44545. vertexData.applyToMesh(tiledGround, options.updatable);
  44546. return tiledGround;
  44547. };
  44548. /**
  44549. * Creates a ground mesh from a height map.
  44550. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  44551. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  44552. * The parameter `url` sets the URL of the height map image resource.
  44553. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  44554. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  44555. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  44556. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  44557. * 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.
  44558. * 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).
  44559. * This function is passed the newly built mesh :
  44560. * ```javascript
  44561. * function(mesh) { // do things
  44562. * return; }
  44563. * ```
  44564. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44565. */
  44566. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  44567. var width = options.width || 10.0;
  44568. var height = options.height || 10.0;
  44569. var subdivisions = options.subdivisions || 1 | 0;
  44570. var minHeight = options.minHeight || 0.0;
  44571. var maxHeight = options.maxHeight || 1.0;
  44572. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  44573. var updatable = options.updatable;
  44574. var onReady = options.onReady;
  44575. var ground = new BABYLON.GroundMesh(name, scene);
  44576. ground._subdivisionsX = subdivisions;
  44577. ground._subdivisionsY = subdivisions;
  44578. ground._width = width;
  44579. ground._height = height;
  44580. ground._maxX = ground._width / 2.0;
  44581. ground._maxZ = ground._height / 2.0;
  44582. ground._minX = -ground._maxX;
  44583. ground._minZ = -ground._maxZ;
  44584. ground._setReady(false);
  44585. var onload = function (img) {
  44586. // Getting height map data
  44587. var canvas = document.createElement("canvas");
  44588. var context = canvas.getContext("2d");
  44589. var bufferWidth = img.width;
  44590. var bufferHeight = img.height;
  44591. canvas.width = bufferWidth;
  44592. canvas.height = bufferHeight;
  44593. context.drawImage(img, 0, 0);
  44594. // Create VertexData from map data
  44595. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  44596. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  44597. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  44598. width: width, height: height,
  44599. subdivisions: subdivisions,
  44600. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  44601. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  44602. });
  44603. vertexData.applyToMesh(ground, updatable);
  44604. ground._setReady(true);
  44605. //execute ready callback, if set
  44606. if (onReady) {
  44607. onReady(ground);
  44608. }
  44609. };
  44610. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  44611. return ground;
  44612. };
  44613. /**
  44614. * Creates a polygon mesh.
  44615. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  44616. * 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.
  44617. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44618. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44619. * 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).
  44620. * Remember you can only change the shape positions, not their number when updating a polygon.
  44621. */
  44622. MeshBuilder.CreatePolygon = function (name, options, scene) {
  44623. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44624. var shape = options.shape;
  44625. var holes = options.holes || [];
  44626. var depth = options.depth || 0;
  44627. var contours = [];
  44628. var hole = [];
  44629. for (var i = 0; i < shape.length; i++) {
  44630. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  44631. }
  44632. var epsilon = 0.00000001;
  44633. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  44634. contours.pop();
  44635. }
  44636. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  44637. for (var hNb = 0; hNb < holes.length; hNb++) {
  44638. hole = [];
  44639. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  44640. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  44641. }
  44642. polygonTriangulation.addHole(hole);
  44643. }
  44644. var polygon = polygonTriangulation.build(options.updatable, depth);
  44645. polygon._originalBuilderSideOrientation = options.sideOrientation;
  44646. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  44647. vertexData.applyToMesh(polygon, options.updatable);
  44648. return polygon;
  44649. };
  44650. ;
  44651. /**
  44652. * Creates an extruded polygon mesh, with depth in the Y direction.
  44653. * 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).
  44654. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  44655. */
  44656. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  44657. return MeshBuilder.CreatePolygon(name, options, scene);
  44658. };
  44659. ;
  44660. /**
  44661. * Creates a tube mesh.
  44662. * 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.
  44663. *
  44664. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  44665. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  44666. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  44667. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  44668. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  44669. * 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.
  44670. * It must return a radius value (positive float) :
  44671. * ```javascript
  44672. * var radiusFunction = function(i, distance) {
  44673. * // do things
  44674. * return radius; }
  44675. * ```
  44676. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  44677. * 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
  44678. * 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
  44679. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44680. * 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).
  44681. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44682. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44683. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44684. */
  44685. MeshBuilder.CreateTube = function (name, options, scene) {
  44686. var path = options.path;
  44687. var instance = options.instance;
  44688. var radius = 1.0;
  44689. if (instance) {
  44690. radius = instance.radius;
  44691. }
  44692. if (options.radius !== undefined) {
  44693. radius = options.radius;
  44694. }
  44695. ;
  44696. var tessellation = options.tessellation || 64 | 0;
  44697. var radiusFunction = options.radiusFunction;
  44698. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  44699. var invertUV = options.invertUV || false;
  44700. var updatable = options.updatable;
  44701. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44702. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  44703. // tube geometry
  44704. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  44705. var tangents = path3D.getTangents();
  44706. var normals = path3D.getNormals();
  44707. var distances = path3D.getDistances();
  44708. var pi2 = Math.PI * 2;
  44709. var step = pi2 / tessellation * arc;
  44710. var returnRadius = function () { return radius; };
  44711. var radiusFunctionFinal = radiusFunction || returnRadius;
  44712. var circlePath;
  44713. var rad;
  44714. var normal;
  44715. var rotated;
  44716. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  44717. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  44718. for (var i = 0; i < path.length; i++) {
  44719. rad = radiusFunctionFinal(i, distances[i]); // current radius
  44720. circlePath = Array(); // current circle array
  44721. normal = normals[i]; // current normal
  44722. for (var t = 0; t < tessellation; t++) {
  44723. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  44724. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  44725. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  44726. rotated.scaleInPlace(rad).addInPlace(path[i]);
  44727. circlePath[t] = rotated;
  44728. }
  44729. circlePaths[index] = circlePath;
  44730. index++;
  44731. }
  44732. // cap
  44733. var capPath = function (nbPoints, pathIndex) {
  44734. var pointCap = Array();
  44735. for (var i = 0; i < nbPoints; i++) {
  44736. pointCap.push(path[pathIndex]);
  44737. }
  44738. return pointCap;
  44739. };
  44740. switch (cap) {
  44741. case BABYLON.Mesh.NO_CAP:
  44742. break;
  44743. case BABYLON.Mesh.CAP_START:
  44744. circlePaths[0] = capPath(tessellation, 0);
  44745. circlePaths[1] = circlePaths[2].slice(0);
  44746. break;
  44747. case BABYLON.Mesh.CAP_END:
  44748. circlePaths[index] = circlePaths[index - 1].slice(0);
  44749. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  44750. break;
  44751. case BABYLON.Mesh.CAP_ALL:
  44752. circlePaths[0] = capPath(tessellation, 0);
  44753. circlePaths[1] = circlePaths[2].slice(0);
  44754. circlePaths[index] = circlePaths[index - 1].slice(0);
  44755. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  44756. break;
  44757. default:
  44758. break;
  44759. }
  44760. return circlePaths;
  44761. };
  44762. var path3D;
  44763. var pathArray;
  44764. if (instance) {
  44765. var arc = options.arc || instance.arc;
  44766. path3D = (instance.path3D).update(path);
  44767. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  44768. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  44769. instance.path3D = path3D;
  44770. instance.pathArray = pathArray;
  44771. instance.arc = arc;
  44772. instance.radius = radius;
  44773. return instance;
  44774. }
  44775. // tube creation
  44776. path3D = new BABYLON.Path3D(path);
  44777. var newPathArray = new Array();
  44778. cap = (cap < 0 || cap > 3) ? 0 : cap;
  44779. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  44780. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  44781. tube.pathArray = pathArray;
  44782. tube.path3D = path3D;
  44783. tube.tessellation = tessellation;
  44784. tube.cap = cap;
  44785. tube.arc = options.arc;
  44786. tube.radius = radius;
  44787. return tube;
  44788. };
  44789. /**
  44790. * Creates a polyhedron mesh.
  44791. *
  44792. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  44793. * 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
  44794. * to choose the wanted type.
  44795. * The parameter `size` (positive float, default 1) sets the polygon size.
  44796. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  44797. * 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`.
  44798. * 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
  44799. * 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)`).
  44800. * 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
  44801. * 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.
  44802. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44803. * 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).
  44804. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44805. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44806. */
  44807. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  44808. var polyhedron = new BABYLON.Mesh(name, scene);
  44809. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44810. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  44811. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  44812. vertexData.applyToMesh(polyhedron, options.updatable);
  44813. return polyhedron;
  44814. };
  44815. /**
  44816. * Creates a decal mesh.
  44817. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  44818. * 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.
  44819. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  44820. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  44821. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  44822. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  44823. */
  44824. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  44825. var indices = sourceMesh.getIndices();
  44826. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44827. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44828. var position = options.position || BABYLON.Vector3.Zero();
  44829. var normal = options.normal || BABYLON.Vector3.Up();
  44830. var size = options.size || BABYLON.Vector3.One();
  44831. var angle = options.angle || 0;
  44832. // Getting correct rotation
  44833. if (!normal) {
  44834. var target = new BABYLON.Vector3(0, 0, 1);
  44835. var camera = sourceMesh.getScene().activeCamera;
  44836. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  44837. normal = camera.globalPosition.subtract(cameraWorldTarget);
  44838. }
  44839. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  44840. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  44841. var pitch = Math.atan2(normal.y, len);
  44842. // Matrix
  44843. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  44844. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  44845. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  44846. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  44847. var vertexData = new BABYLON.VertexData();
  44848. vertexData.indices = [];
  44849. vertexData.positions = [];
  44850. vertexData.normals = [];
  44851. vertexData.uvs = [];
  44852. var currentVertexDataIndex = 0;
  44853. var extractDecalVector3 = function (indexId) {
  44854. var vertexId = indices[indexId];
  44855. var result = new BABYLON.PositionNormalVertex();
  44856. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  44857. // Send vector to decal local world
  44858. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  44859. // Get normal
  44860. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  44861. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  44862. return result;
  44863. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  44864. var clip = function (vertices, axis) {
  44865. if (vertices.length === 0) {
  44866. return vertices;
  44867. }
  44868. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  44869. var clipVertices = function (v0, v1) {
  44870. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  44871. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  44872. };
  44873. var result = new Array();
  44874. for (var index = 0; index < vertices.length; index += 3) {
  44875. var v1Out;
  44876. var v2Out;
  44877. var v3Out;
  44878. var total = 0;
  44879. var nV1, nV2, nV3, nV4;
  44880. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  44881. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  44882. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  44883. v1Out = d1 > 0;
  44884. v2Out = d2 > 0;
  44885. v3Out = d3 > 0;
  44886. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  44887. switch (total) {
  44888. case 0:
  44889. result.push(vertices[index]);
  44890. result.push(vertices[index + 1]);
  44891. result.push(vertices[index + 2]);
  44892. break;
  44893. case 1:
  44894. if (v1Out) {
  44895. nV1 = vertices[index + 1];
  44896. nV2 = vertices[index + 2];
  44897. nV3 = clipVertices(vertices[index], nV1);
  44898. nV4 = clipVertices(vertices[index], nV2);
  44899. }
  44900. if (v2Out) {
  44901. nV1 = vertices[index];
  44902. nV2 = vertices[index + 2];
  44903. nV3 = clipVertices(vertices[index + 1], nV1);
  44904. nV4 = clipVertices(vertices[index + 1], nV2);
  44905. result.push(nV3);
  44906. result.push(nV2.clone());
  44907. result.push(nV1.clone());
  44908. result.push(nV2.clone());
  44909. result.push(nV3.clone());
  44910. result.push(nV4);
  44911. break;
  44912. }
  44913. if (v3Out) {
  44914. nV1 = vertices[index];
  44915. nV2 = vertices[index + 1];
  44916. nV3 = clipVertices(vertices[index + 2], nV1);
  44917. nV4 = clipVertices(vertices[index + 2], nV2);
  44918. }
  44919. result.push(nV1.clone());
  44920. result.push(nV2.clone());
  44921. result.push(nV3);
  44922. result.push(nV4);
  44923. result.push(nV3.clone());
  44924. result.push(nV2.clone());
  44925. break;
  44926. case 2:
  44927. if (!v1Out) {
  44928. nV1 = vertices[index].clone();
  44929. nV2 = clipVertices(nV1, vertices[index + 1]);
  44930. nV3 = clipVertices(nV1, vertices[index + 2]);
  44931. result.push(nV1);
  44932. result.push(nV2);
  44933. result.push(nV3);
  44934. }
  44935. if (!v2Out) {
  44936. nV1 = vertices[index + 1].clone();
  44937. nV2 = clipVertices(nV1, vertices[index + 2]);
  44938. nV3 = clipVertices(nV1, vertices[index]);
  44939. result.push(nV1);
  44940. result.push(nV2);
  44941. result.push(nV3);
  44942. }
  44943. if (!v3Out) {
  44944. nV1 = vertices[index + 2].clone();
  44945. nV2 = clipVertices(nV1, vertices[index]);
  44946. nV3 = clipVertices(nV1, vertices[index + 1]);
  44947. result.push(nV1);
  44948. result.push(nV2);
  44949. result.push(nV3);
  44950. }
  44951. break;
  44952. case 3:
  44953. break;
  44954. }
  44955. }
  44956. return result;
  44957. };
  44958. for (var index = 0; index < indices.length; index += 3) {
  44959. var faceVertices = new Array();
  44960. faceVertices.push(extractDecalVector3(index));
  44961. faceVertices.push(extractDecalVector3(index + 1));
  44962. faceVertices.push(extractDecalVector3(index + 2));
  44963. // Clip
  44964. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  44965. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  44966. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  44967. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  44968. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  44969. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  44970. if (faceVertices.length === 0) {
  44971. continue;
  44972. }
  44973. // Add UVs and get back to world
  44974. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  44975. var vertex = faceVertices[vIndex];
  44976. //TODO check for Int32Array | Uint32Array | Uint16Array
  44977. vertexData.indices.push(currentVertexDataIndex);
  44978. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  44979. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  44980. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  44981. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  44982. currentVertexDataIndex++;
  44983. }
  44984. }
  44985. // Return mesh
  44986. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  44987. vertexData.applyToMesh(decal);
  44988. decal.position = position.clone();
  44989. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  44990. return decal;
  44991. };
  44992. // Privates
  44993. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  44994. // extrusion geometry
  44995. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  44996. var tangents = path3D.getTangents();
  44997. var normals = path3D.getNormals();
  44998. var binormals = path3D.getBinormals();
  44999. var distances = path3D.getDistances();
  45000. var angle = 0;
  45001. var returnScale = function () { return scale; };
  45002. var returnRotation = function () { return rotation; };
  45003. var rotate = custom ? rotateFunction : returnRotation;
  45004. var scl = custom ? scaleFunction : returnScale;
  45005. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  45006. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  45007. for (var i = 0; i < curve.length; i++) {
  45008. var shapePath = new Array();
  45009. var angleStep = rotate(i, distances[i]);
  45010. var scaleRatio = scl(i, distances[i]);
  45011. for (var p = 0; p < shape.length; p++) {
  45012. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  45013. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  45014. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  45015. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  45016. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  45017. shapePath[p] = rotated;
  45018. }
  45019. shapePaths[index] = shapePath;
  45020. angle += angleStep;
  45021. index++;
  45022. }
  45023. // cap
  45024. var capPath = function (shapePath) {
  45025. var pointCap = Array();
  45026. var barycenter = BABYLON.Vector3.Zero();
  45027. var i;
  45028. for (i = 0; i < shapePath.length; i++) {
  45029. barycenter.addInPlace(shapePath[i]);
  45030. }
  45031. barycenter.scaleInPlace(1.0 / shapePath.length);
  45032. for (i = 0; i < shapePath.length; i++) {
  45033. pointCap.push(barycenter);
  45034. }
  45035. return pointCap;
  45036. };
  45037. switch (cap) {
  45038. case BABYLON.Mesh.NO_CAP:
  45039. break;
  45040. case BABYLON.Mesh.CAP_START:
  45041. shapePaths[0] = capPath(shapePaths[2]);
  45042. shapePaths[1] = shapePaths[2];
  45043. break;
  45044. case BABYLON.Mesh.CAP_END:
  45045. shapePaths[index] = shapePaths[index - 1];
  45046. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  45047. break;
  45048. case BABYLON.Mesh.CAP_ALL:
  45049. shapePaths[0] = capPath(shapePaths[2]);
  45050. shapePaths[1] = shapePaths[2];
  45051. shapePaths[index] = shapePaths[index - 1];
  45052. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  45053. break;
  45054. default:
  45055. break;
  45056. }
  45057. return shapePaths;
  45058. };
  45059. var path3D;
  45060. var pathArray;
  45061. if (instance) {
  45062. path3D = (instance.path3D).update(curve);
  45063. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  45064. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  45065. return instance;
  45066. }
  45067. // extruded shape creation
  45068. path3D = new BABYLON.Path3D(curve);
  45069. var newShapePaths = new Array();
  45070. cap = (cap < 0 || cap > 3) ? 0 : cap;
  45071. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  45072. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  45073. extrudedGeneric.pathArray = pathArray;
  45074. extrudedGeneric.path3D = path3D;
  45075. extrudedGeneric.cap = cap;
  45076. return extrudedGeneric;
  45077. };
  45078. return MeshBuilder;
  45079. }());
  45080. BABYLON.MeshBuilder = MeshBuilder;
  45081. })(BABYLON || (BABYLON = {}));
  45082. //# sourceMappingURL=babylon.meshBuilder.js.map
  45083. var BABYLON;
  45084. (function (BABYLON) {
  45085. var AudioEngine = (function () {
  45086. function AudioEngine() {
  45087. this._audioContext = null;
  45088. this._audioContextInitialized = false;
  45089. this.canUseWebAudio = false;
  45090. this.WarnedWebAudioUnsupported = false;
  45091. this.unlocked = false;
  45092. this.isMP3supported = false;
  45093. this.isOGGsupported = false;
  45094. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  45095. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  45096. this.canUseWebAudio = true;
  45097. }
  45098. var audioElem = document.createElement('audio');
  45099. try {
  45100. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  45101. this.isMP3supported = true;
  45102. }
  45103. }
  45104. catch (e) {
  45105. // protect error during capability check.
  45106. }
  45107. try {
  45108. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  45109. this.isOGGsupported = true;
  45110. }
  45111. }
  45112. catch (e) {
  45113. // protect error during capability check.
  45114. }
  45115. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  45116. this._unlockiOSaudio();
  45117. }
  45118. else {
  45119. this.unlocked = true;
  45120. }
  45121. }
  45122. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  45123. get: function () {
  45124. if (!this._audioContextInitialized) {
  45125. this._initializeAudioContext();
  45126. }
  45127. return this._audioContext;
  45128. },
  45129. enumerable: true,
  45130. configurable: true
  45131. });
  45132. AudioEngine.prototype._unlockiOSaudio = function () {
  45133. var _this = this;
  45134. var unlockaudio = function () {
  45135. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  45136. var source = _this.audioContext.createBufferSource();
  45137. source.buffer = buffer;
  45138. source.connect(_this.audioContext.destination);
  45139. source.start(0);
  45140. setTimeout(function () {
  45141. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  45142. _this.unlocked = true;
  45143. window.removeEventListener('touchend', unlockaudio, false);
  45144. if (_this.onAudioUnlocked) {
  45145. _this.onAudioUnlocked();
  45146. }
  45147. }
  45148. }, 0);
  45149. };
  45150. window.addEventListener('touchend', unlockaudio, false);
  45151. };
  45152. AudioEngine.prototype._initializeAudioContext = function () {
  45153. try {
  45154. if (this.canUseWebAudio) {
  45155. this._audioContext = new AudioContext();
  45156. // create a global volume gain node
  45157. this.masterGain = this._audioContext.createGain();
  45158. this.masterGain.gain.value = 1;
  45159. this.masterGain.connect(this._audioContext.destination);
  45160. this._audioContextInitialized = true;
  45161. }
  45162. }
  45163. catch (e) {
  45164. this.canUseWebAudio = false;
  45165. BABYLON.Tools.Error("Web Audio: " + e.message);
  45166. }
  45167. };
  45168. AudioEngine.prototype.dispose = function () {
  45169. if (this.canUseWebAudio && this._audioContextInitialized) {
  45170. if (this._connectedAnalyser) {
  45171. this._connectedAnalyser.stopDebugCanvas();
  45172. this._connectedAnalyser.dispose();
  45173. this.masterGain.disconnect();
  45174. this.masterGain.connect(this._audioContext.destination);
  45175. this._connectedAnalyser = null;
  45176. }
  45177. this.masterGain.gain.value = 1;
  45178. }
  45179. this.WarnedWebAudioUnsupported = false;
  45180. };
  45181. AudioEngine.prototype.getGlobalVolume = function () {
  45182. if (this.canUseWebAudio && this._audioContextInitialized) {
  45183. return this.masterGain.gain.value;
  45184. }
  45185. else {
  45186. return -1;
  45187. }
  45188. };
  45189. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  45190. if (this.canUseWebAudio && this._audioContextInitialized) {
  45191. this.masterGain.gain.value = newVolume;
  45192. }
  45193. };
  45194. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  45195. if (this._connectedAnalyser) {
  45196. this._connectedAnalyser.stopDebugCanvas();
  45197. }
  45198. if (this.canUseWebAudio && this._audioContextInitialized) {
  45199. this._connectedAnalyser = analyser;
  45200. this.masterGain.disconnect();
  45201. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  45202. }
  45203. };
  45204. return AudioEngine;
  45205. }());
  45206. BABYLON.AudioEngine = AudioEngine;
  45207. })(BABYLON || (BABYLON = {}));
  45208. //# sourceMappingURL=babylon.audioEngine.js.map
  45209. var BABYLON;
  45210. (function (BABYLON) {
  45211. var Sound = (function () {
  45212. /**
  45213. * Create a sound and attach it to a scene
  45214. * @param name Name of your sound
  45215. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  45216. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  45217. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  45218. */
  45219. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  45220. var _this = this;
  45221. this.autoplay = false;
  45222. this.loop = false;
  45223. this.useCustomAttenuation = false;
  45224. this.spatialSound = false;
  45225. this.refDistance = 1;
  45226. this.rolloffFactor = 1;
  45227. this.maxDistance = 100;
  45228. this.distanceModel = "linear";
  45229. this._panningModel = "equalpower";
  45230. this._playbackRate = 1;
  45231. this._streaming = false;
  45232. this._startTime = 0;
  45233. this._startOffset = 0;
  45234. this._position = BABYLON.Vector3.Zero();
  45235. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  45236. this._volume = 1;
  45237. this._isLoaded = false;
  45238. this._isReadyToPlay = false;
  45239. this.isPlaying = false;
  45240. this.isPaused = false;
  45241. this._isDirectional = false;
  45242. // Used if you'd like to create a directional sound.
  45243. // If not set, the sound will be omnidirectional
  45244. this._coneInnerAngle = 360;
  45245. this._coneOuterAngle = 360;
  45246. this._coneOuterGain = 0;
  45247. this._isOutputConnected = false;
  45248. this._urlType = "Unknown";
  45249. this.name = name;
  45250. this._scene = scene;
  45251. this._readyToPlayCallback = readyToPlayCallback;
  45252. // Default custom attenuation function is a linear attenuation
  45253. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  45254. if (currentDistance < maxDistance) {
  45255. return currentVolume * (1 - currentDistance / maxDistance);
  45256. }
  45257. else {
  45258. return 0;
  45259. }
  45260. };
  45261. if (options) {
  45262. this.autoplay = options.autoplay || false;
  45263. this.loop = options.loop || false;
  45264. // if volume === 0, we need another way to check this option
  45265. if (options.volume !== undefined) {
  45266. this._volume = options.volume;
  45267. }
  45268. this.spatialSound = options.spatialSound || false;
  45269. this.maxDistance = options.maxDistance || 100;
  45270. this.useCustomAttenuation = options.useCustomAttenuation || false;
  45271. this.rolloffFactor = options.rolloffFactor || 1;
  45272. this.refDistance = options.refDistance || 1;
  45273. this.distanceModel = options.distanceModel || "linear";
  45274. this._playbackRate = options.playbackRate || 1;
  45275. this._streaming = options.streaming || false;
  45276. }
  45277. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45278. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  45279. this._soundGain.gain.value = this._volume;
  45280. this._inputAudioNode = this._soundGain;
  45281. this._ouputAudioNode = this._soundGain;
  45282. if (this.spatialSound) {
  45283. this._createSpatialParameters();
  45284. }
  45285. this._scene.mainSoundTrack.AddSound(this);
  45286. var validParameter = true;
  45287. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  45288. if (urlOrArrayBuffer) {
  45289. if (typeof (urlOrArrayBuffer) === "string")
  45290. this._urlType = "String";
  45291. if (Array.isArray(urlOrArrayBuffer))
  45292. this._urlType = "Array";
  45293. if (urlOrArrayBuffer instanceof ArrayBuffer)
  45294. this._urlType = "ArrayBuffer";
  45295. var urls = [];
  45296. var codecSupportedFound = false;
  45297. switch (this._urlType) {
  45298. case "ArrayBuffer":
  45299. if (urlOrArrayBuffer.byteLength > 0) {
  45300. codecSupportedFound = true;
  45301. this._soundLoaded(urlOrArrayBuffer);
  45302. }
  45303. break;
  45304. case "String":
  45305. urls.push(urlOrArrayBuffer);
  45306. case "Array":
  45307. if (urls.length === 0)
  45308. urls = urlOrArrayBuffer;
  45309. // If we found a supported format, we load it immediately and stop the loop
  45310. for (var i = 0; i < urls.length; i++) {
  45311. var url = urls[i];
  45312. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  45313. codecSupportedFound = true;
  45314. }
  45315. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  45316. codecSupportedFound = true;
  45317. }
  45318. if (url.indexOf(".wav", url.length - 4) !== -1) {
  45319. codecSupportedFound = true;
  45320. }
  45321. if (url.indexOf("blob:") !== -1) {
  45322. codecSupportedFound = true;
  45323. }
  45324. if (codecSupportedFound) {
  45325. // Loading sound using XHR2
  45326. if (!this._streaming) {
  45327. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  45328. }
  45329. else {
  45330. this._htmlAudioElement = new Audio(url);
  45331. this._htmlAudioElement.controls = false;
  45332. this._htmlAudioElement.loop = this.loop;
  45333. this._htmlAudioElement.crossOrigin = "anonymous";
  45334. this._htmlAudioElement.preload = "auto";
  45335. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  45336. _this._isReadyToPlay = true;
  45337. if (_this.autoplay) {
  45338. _this.play();
  45339. }
  45340. if (_this._readyToPlayCallback) {
  45341. _this._readyToPlayCallback();
  45342. }
  45343. });
  45344. document.body.appendChild(this._htmlAudioElement);
  45345. }
  45346. break;
  45347. }
  45348. }
  45349. break;
  45350. default:
  45351. validParameter = false;
  45352. break;
  45353. }
  45354. if (!validParameter) {
  45355. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  45356. }
  45357. else {
  45358. if (!codecSupportedFound) {
  45359. this._isReadyToPlay = true;
  45360. // Simulating a ready to play event to avoid breaking code path
  45361. if (this._readyToPlayCallback) {
  45362. window.setTimeout(function () {
  45363. _this._readyToPlayCallback();
  45364. }, 1000);
  45365. }
  45366. }
  45367. }
  45368. }
  45369. }
  45370. else {
  45371. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  45372. this._scene.mainSoundTrack.AddSound(this);
  45373. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  45374. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  45375. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  45376. }
  45377. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  45378. if (this._readyToPlayCallback) {
  45379. window.setTimeout(function () {
  45380. _this._readyToPlayCallback();
  45381. }, 1000);
  45382. }
  45383. }
  45384. }
  45385. Sound.prototype.dispose = function () {
  45386. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  45387. if (this.isPlaying) {
  45388. this.stop();
  45389. }
  45390. this._isReadyToPlay = false;
  45391. if (this.soundTrackId === -1) {
  45392. this._scene.mainSoundTrack.RemoveSound(this);
  45393. }
  45394. else {
  45395. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  45396. }
  45397. if (this._soundGain) {
  45398. this._soundGain.disconnect();
  45399. this._soundGain = null;
  45400. }
  45401. if (this._soundPanner) {
  45402. this._soundPanner.disconnect();
  45403. this._soundPanner = null;
  45404. }
  45405. if (this._soundSource) {
  45406. this._soundSource.disconnect();
  45407. this._soundSource = null;
  45408. }
  45409. this._audioBuffer = null;
  45410. if (this._htmlAudioElement) {
  45411. this._htmlAudioElement.pause();
  45412. this._htmlAudioElement.src = "";
  45413. document.body.removeChild(this._htmlAudioElement);
  45414. }
  45415. if (this._connectedMesh) {
  45416. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45417. this._connectedMesh = null;
  45418. }
  45419. }
  45420. };
  45421. Sound.prototype.isReady = function () {
  45422. return this._isReadyToPlay;
  45423. };
  45424. Sound.prototype._soundLoaded = function (audioData) {
  45425. var _this = this;
  45426. this._isLoaded = true;
  45427. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  45428. _this._audioBuffer = buffer;
  45429. _this._isReadyToPlay = true;
  45430. if (_this.autoplay) {
  45431. _this.play();
  45432. }
  45433. if (_this._readyToPlayCallback) {
  45434. _this._readyToPlayCallback();
  45435. }
  45436. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  45437. };
  45438. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  45439. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45440. this._audioBuffer = audioBuffer;
  45441. this._isReadyToPlay = true;
  45442. }
  45443. };
  45444. Sound.prototype.updateOptions = function (options) {
  45445. if (options) {
  45446. this.loop = options.loop || this.loop;
  45447. this.maxDistance = options.maxDistance || this.maxDistance;
  45448. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  45449. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  45450. this.refDistance = options.refDistance || this.refDistance;
  45451. this.distanceModel = options.distanceModel || this.distanceModel;
  45452. this._playbackRate = options.playbackRate || this._playbackRate;
  45453. this._updateSpatialParameters();
  45454. if (this.isPlaying) {
  45455. if (this._streaming) {
  45456. this._htmlAudioElement.playbackRate = this._playbackRate;
  45457. }
  45458. else {
  45459. this._soundSource.playbackRate.value = this._playbackRate;
  45460. }
  45461. }
  45462. }
  45463. };
  45464. Sound.prototype._createSpatialParameters = function () {
  45465. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45466. if (this._scene.headphone) {
  45467. this._panningModel = "HRTF";
  45468. }
  45469. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  45470. this._updateSpatialParameters();
  45471. this._soundPanner.connect(this._ouputAudioNode);
  45472. this._inputAudioNode = this._soundPanner;
  45473. }
  45474. };
  45475. Sound.prototype._updateSpatialParameters = function () {
  45476. if (this.spatialSound) {
  45477. if (this.useCustomAttenuation) {
  45478. // Tricks to disable in a way embedded Web Audio attenuation
  45479. this._soundPanner.distanceModel = "linear";
  45480. this._soundPanner.maxDistance = Number.MAX_VALUE;
  45481. this._soundPanner.refDistance = 1;
  45482. this._soundPanner.rolloffFactor = 1;
  45483. this._soundPanner.panningModel = this._panningModel;
  45484. }
  45485. else {
  45486. this._soundPanner.distanceModel = this.distanceModel;
  45487. this._soundPanner.maxDistance = this.maxDistance;
  45488. this._soundPanner.refDistance = this.refDistance;
  45489. this._soundPanner.rolloffFactor = this.rolloffFactor;
  45490. this._soundPanner.panningModel = this._panningModel;
  45491. }
  45492. }
  45493. };
  45494. Sound.prototype.switchPanningModelToHRTF = function () {
  45495. this._panningModel = "HRTF";
  45496. this._switchPanningModel();
  45497. };
  45498. Sound.prototype.switchPanningModelToEqualPower = function () {
  45499. this._panningModel = "equalpower";
  45500. this._switchPanningModel();
  45501. };
  45502. Sound.prototype._switchPanningModel = function () {
  45503. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  45504. this._soundPanner.panningModel = this._panningModel;
  45505. }
  45506. };
  45507. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  45508. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45509. if (this._isOutputConnected) {
  45510. this._ouputAudioNode.disconnect();
  45511. }
  45512. this._ouputAudioNode.connect(soundTrackAudioNode);
  45513. this._isOutputConnected = true;
  45514. }
  45515. };
  45516. /**
  45517. * Transform this sound into a directional source
  45518. * @param coneInnerAngle Size of the inner cone in degree
  45519. * @param coneOuterAngle Size of the outer cone in degree
  45520. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  45521. */
  45522. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  45523. if (coneOuterAngle < coneInnerAngle) {
  45524. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  45525. return;
  45526. }
  45527. this._coneInnerAngle = coneInnerAngle;
  45528. this._coneOuterAngle = coneOuterAngle;
  45529. this._coneOuterGain = coneOuterGain;
  45530. this._isDirectional = true;
  45531. if (this.isPlaying && this.loop) {
  45532. this.stop();
  45533. this.play();
  45534. }
  45535. };
  45536. Sound.prototype.setPosition = function (newPosition) {
  45537. this._position = newPosition;
  45538. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  45539. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  45540. }
  45541. };
  45542. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  45543. this._localDirection = newLocalDirection;
  45544. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  45545. this._updateDirection();
  45546. }
  45547. };
  45548. Sound.prototype._updateDirection = function () {
  45549. var mat = this._connectedMesh.getWorldMatrix();
  45550. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  45551. direction.normalize();
  45552. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  45553. };
  45554. Sound.prototype.updateDistanceFromListener = function () {
  45555. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  45556. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  45557. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  45558. }
  45559. };
  45560. Sound.prototype.setAttenuationFunction = function (callback) {
  45561. this._customAttenuationFunction = callback;
  45562. };
  45563. /**
  45564. * Play the sound
  45565. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  45566. * @param offset (optional) Start the sound setting it at a specific time
  45567. */
  45568. Sound.prototype.play = function (time, offset) {
  45569. var _this = this;
  45570. if (this._isReadyToPlay && this._scene.audioEnabled) {
  45571. try {
  45572. if (this._startOffset < 0) {
  45573. time = -this._startOffset;
  45574. this._startOffset = 0;
  45575. }
  45576. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  45577. if (!this._soundSource || !this._streamingSource) {
  45578. if (this.spatialSound) {
  45579. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  45580. if (this._isDirectional) {
  45581. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  45582. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  45583. this._soundPanner.coneOuterGain = this._coneOuterGain;
  45584. if (this._connectedMesh) {
  45585. this._updateDirection();
  45586. }
  45587. else {
  45588. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  45589. }
  45590. }
  45591. }
  45592. }
  45593. if (this._streaming) {
  45594. if (!this._streamingSource) {
  45595. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  45596. this._htmlAudioElement.onended = function () { _this._onended(); };
  45597. this._htmlAudioElement.playbackRate = this._playbackRate;
  45598. }
  45599. this._streamingSource.disconnect();
  45600. this._streamingSource.connect(this._inputAudioNode);
  45601. this._htmlAudioElement.play();
  45602. }
  45603. else {
  45604. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  45605. this._soundSource.buffer = this._audioBuffer;
  45606. this._soundSource.connect(this._inputAudioNode);
  45607. this._soundSource.loop = this.loop;
  45608. this._soundSource.playbackRate.value = this._playbackRate;
  45609. this._soundSource.onended = function () { _this._onended(); };
  45610. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  45611. }
  45612. this._startTime = startTime;
  45613. this.isPlaying = true;
  45614. this.isPaused = false;
  45615. }
  45616. catch (ex) {
  45617. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  45618. }
  45619. }
  45620. };
  45621. Sound.prototype._onended = function () {
  45622. this.isPlaying = false;
  45623. if (this.onended) {
  45624. this.onended();
  45625. }
  45626. };
  45627. /**
  45628. * Stop the sound
  45629. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  45630. */
  45631. Sound.prototype.stop = function (time) {
  45632. if (this.isPlaying) {
  45633. if (this._streaming) {
  45634. this._htmlAudioElement.pause();
  45635. // Test needed for Firefox or it will generate an Invalid State Error
  45636. if (this._htmlAudioElement.currentTime > 0) {
  45637. this._htmlAudioElement.currentTime = 0;
  45638. }
  45639. }
  45640. else {
  45641. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  45642. this._soundSource.stop(stopTime);
  45643. this._soundSource.onended = null;
  45644. if (!this.isPaused) {
  45645. this._startOffset = 0;
  45646. }
  45647. }
  45648. this.isPlaying = false;
  45649. }
  45650. };
  45651. Sound.prototype.pause = function () {
  45652. if (this.isPlaying) {
  45653. this.isPaused = true;
  45654. if (this._streaming) {
  45655. this._htmlAudioElement.pause();
  45656. }
  45657. else {
  45658. this.stop(0);
  45659. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  45660. }
  45661. }
  45662. };
  45663. Sound.prototype.setVolume = function (newVolume, time) {
  45664. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45665. if (time) {
  45666. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  45667. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  45668. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  45669. }
  45670. else {
  45671. this._soundGain.gain.value = newVolume;
  45672. }
  45673. }
  45674. this._volume = newVolume;
  45675. };
  45676. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  45677. this._playbackRate = newPlaybackRate;
  45678. if (this.isPlaying) {
  45679. if (this._streaming) {
  45680. this._htmlAudioElement.playbackRate = this._playbackRate;
  45681. }
  45682. else {
  45683. this._soundSource.playbackRate.value = this._playbackRate;
  45684. }
  45685. }
  45686. };
  45687. Sound.prototype.getVolume = function () {
  45688. return this._volume;
  45689. };
  45690. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  45691. var _this = this;
  45692. if (this._connectedMesh) {
  45693. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45694. this._registerFunc = null;
  45695. }
  45696. this._connectedMesh = meshToConnectTo;
  45697. if (!this.spatialSound) {
  45698. this.spatialSound = true;
  45699. this._createSpatialParameters();
  45700. if (this.isPlaying && this.loop) {
  45701. this.stop();
  45702. this.play();
  45703. }
  45704. }
  45705. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  45706. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  45707. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  45708. };
  45709. Sound.prototype.detachFromMesh = function () {
  45710. if (this._connectedMesh) {
  45711. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45712. this._registerFunc = null;
  45713. this._connectedMesh = null;
  45714. }
  45715. };
  45716. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  45717. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  45718. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  45719. this._updateDirection();
  45720. }
  45721. };
  45722. Sound.prototype.clone = function () {
  45723. var _this = this;
  45724. if (!this._streaming) {
  45725. var setBufferAndRun = function () {
  45726. if (_this._isReadyToPlay) {
  45727. clonedSound._audioBuffer = _this.getAudioBuffer();
  45728. clonedSound._isReadyToPlay = true;
  45729. if (clonedSound.autoplay) {
  45730. clonedSound.play();
  45731. }
  45732. }
  45733. else {
  45734. window.setTimeout(setBufferAndRun, 300);
  45735. }
  45736. };
  45737. var currentOptions = {
  45738. autoplay: this.autoplay, loop: this.loop,
  45739. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  45740. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  45741. refDistance: this.refDistance, distanceModel: this.distanceModel
  45742. };
  45743. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  45744. if (this.useCustomAttenuation) {
  45745. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  45746. }
  45747. clonedSound.setPosition(this._position);
  45748. clonedSound.setPlaybackRate(this._playbackRate);
  45749. setBufferAndRun();
  45750. return clonedSound;
  45751. }
  45752. else {
  45753. return null;
  45754. }
  45755. };
  45756. Sound.prototype.getAudioBuffer = function () {
  45757. return this._audioBuffer;
  45758. };
  45759. Sound.prototype.serialize = function () {
  45760. var serializationObject = {
  45761. name: this.name,
  45762. url: this.name,
  45763. autoplay: this.autoplay,
  45764. loop: this.loop,
  45765. volume: this._volume,
  45766. spatialSound: this.spatialSound,
  45767. maxDistance: this.maxDistance,
  45768. rolloffFactor: this.rolloffFactor,
  45769. refDistance: this.refDistance,
  45770. distanceModel: this.distanceModel,
  45771. playbackRate: this._playbackRate,
  45772. panningModel: this._panningModel,
  45773. soundTrackId: this.soundTrackId
  45774. };
  45775. if (this.spatialSound) {
  45776. if (this._connectedMesh)
  45777. serializationObject.connectedMeshId = this._connectedMesh.id;
  45778. serializationObject.position = this._position.asArray();
  45779. serializationObject.refDistance = this.refDistance;
  45780. serializationObject.distanceModel = this.distanceModel;
  45781. serializationObject.isDirectional = this._isDirectional;
  45782. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  45783. serializationObject.coneInnerAngle = this._coneInnerAngle;
  45784. serializationObject.coneOuterAngle = this._coneOuterAngle;
  45785. serializationObject.coneOuterGain = this._coneOuterGain;
  45786. }
  45787. return serializationObject;
  45788. };
  45789. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  45790. var soundName = parsedSound.name;
  45791. var soundUrl;
  45792. if (parsedSound.url) {
  45793. soundUrl = rootUrl + parsedSound.url;
  45794. }
  45795. else {
  45796. soundUrl = rootUrl + soundName;
  45797. }
  45798. var options = {
  45799. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  45800. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  45801. rolloffFactor: parsedSound.rolloffFactor,
  45802. refDistance: parsedSound.refDistance,
  45803. distanceModel: parsedSound.distanceModel,
  45804. playbackRate: parsedSound.playbackRate
  45805. };
  45806. var newSound;
  45807. if (!sourceSound) {
  45808. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  45809. scene._addPendingData(newSound);
  45810. }
  45811. else {
  45812. var setBufferAndRun = function () {
  45813. if (sourceSound._isReadyToPlay) {
  45814. newSound._audioBuffer = sourceSound.getAudioBuffer();
  45815. newSound._isReadyToPlay = true;
  45816. if (newSound.autoplay) {
  45817. newSound.play();
  45818. }
  45819. }
  45820. else {
  45821. window.setTimeout(setBufferAndRun, 300);
  45822. }
  45823. };
  45824. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  45825. setBufferAndRun();
  45826. }
  45827. if (parsedSound.position) {
  45828. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  45829. newSound.setPosition(soundPosition);
  45830. }
  45831. if (parsedSound.isDirectional) {
  45832. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  45833. if (parsedSound.localDirectionToMesh) {
  45834. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  45835. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  45836. }
  45837. }
  45838. if (parsedSound.connectedMeshId) {
  45839. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  45840. if (connectedMesh) {
  45841. newSound.attachToMesh(connectedMesh);
  45842. }
  45843. }
  45844. return newSound;
  45845. };
  45846. return Sound;
  45847. }());
  45848. BABYLON.Sound = Sound;
  45849. })(BABYLON || (BABYLON = {}));
  45850. //# sourceMappingURL=babylon.sound.js.map
  45851. var BABYLON;
  45852. (function (BABYLON) {
  45853. var SoundTrack = (function () {
  45854. function SoundTrack(scene, options) {
  45855. this.id = -1;
  45856. this._isMainTrack = false;
  45857. this._isInitialized = false;
  45858. this._scene = scene;
  45859. this.soundCollection = new Array();
  45860. this._options = options;
  45861. if (!this._isMainTrack) {
  45862. this._scene.soundTracks.push(this);
  45863. this.id = this._scene.soundTracks.length - 1;
  45864. }
  45865. }
  45866. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  45867. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45868. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  45869. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  45870. if (this._options) {
  45871. if (this._options.volume) {
  45872. this._outputAudioNode.gain.value = this._options.volume;
  45873. }
  45874. if (this._options.mainTrack) {
  45875. this._isMainTrack = this._options.mainTrack;
  45876. }
  45877. }
  45878. this._isInitialized = true;
  45879. }
  45880. };
  45881. SoundTrack.prototype.dispose = function () {
  45882. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45883. if (this._connectedAnalyser) {
  45884. this._connectedAnalyser.stopDebugCanvas();
  45885. }
  45886. while (this.soundCollection.length) {
  45887. this.soundCollection[0].dispose();
  45888. }
  45889. if (this._outputAudioNode) {
  45890. this._outputAudioNode.disconnect();
  45891. }
  45892. this._outputAudioNode = null;
  45893. }
  45894. };
  45895. SoundTrack.prototype.AddSound = function (sound) {
  45896. if (!this._isInitialized) {
  45897. this._initializeSoundTrackAudioGraph();
  45898. }
  45899. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45900. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  45901. }
  45902. if (sound.soundTrackId) {
  45903. if (sound.soundTrackId === -1) {
  45904. this._scene.mainSoundTrack.RemoveSound(sound);
  45905. }
  45906. else {
  45907. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  45908. }
  45909. }
  45910. this.soundCollection.push(sound);
  45911. sound.soundTrackId = this.id;
  45912. };
  45913. SoundTrack.prototype.RemoveSound = function (sound) {
  45914. var index = this.soundCollection.indexOf(sound);
  45915. if (index !== -1) {
  45916. this.soundCollection.splice(index, 1);
  45917. }
  45918. };
  45919. SoundTrack.prototype.setVolume = function (newVolume) {
  45920. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45921. this._outputAudioNode.gain.value = newVolume;
  45922. }
  45923. };
  45924. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  45925. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45926. for (var i = 0; i < this.soundCollection.length; i++) {
  45927. this.soundCollection[i].switchPanningModelToHRTF();
  45928. }
  45929. }
  45930. };
  45931. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  45932. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45933. for (var i = 0; i < this.soundCollection.length; i++) {
  45934. this.soundCollection[i].switchPanningModelToEqualPower();
  45935. }
  45936. }
  45937. };
  45938. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  45939. if (this._connectedAnalyser) {
  45940. this._connectedAnalyser.stopDebugCanvas();
  45941. }
  45942. this._connectedAnalyser = analyser;
  45943. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45944. this._outputAudioNode.disconnect();
  45945. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  45946. }
  45947. };
  45948. return SoundTrack;
  45949. }());
  45950. BABYLON.SoundTrack = SoundTrack;
  45951. })(BABYLON || (BABYLON = {}));
  45952. //# sourceMappingURL=babylon.soundtrack.js.map
  45953. var BABYLON;
  45954. (function (BABYLON) {
  45955. var Analyser = (function () {
  45956. function Analyser(scene) {
  45957. this.SMOOTHING = 0.75;
  45958. this.FFT_SIZE = 512;
  45959. this.BARGRAPHAMPLITUDE = 256;
  45960. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  45961. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  45962. this._scene = scene;
  45963. this._audioEngine = BABYLON.Engine.audioEngine;
  45964. if (this._audioEngine.canUseWebAudio) {
  45965. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  45966. this._webAudioAnalyser.minDecibels = -140;
  45967. this._webAudioAnalyser.maxDecibels = 0;
  45968. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45969. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45970. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  45971. }
  45972. }
  45973. Analyser.prototype.getFrequencyBinCount = function () {
  45974. if (this._audioEngine.canUseWebAudio) {
  45975. return this._webAudioAnalyser.frequencyBinCount;
  45976. }
  45977. else {
  45978. return 0;
  45979. }
  45980. };
  45981. Analyser.prototype.getByteFrequencyData = function () {
  45982. if (this._audioEngine.canUseWebAudio) {
  45983. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45984. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45985. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  45986. }
  45987. return this._byteFreqs;
  45988. };
  45989. Analyser.prototype.getByteTimeDomainData = function () {
  45990. if (this._audioEngine.canUseWebAudio) {
  45991. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45992. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45993. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  45994. }
  45995. return this._byteTime;
  45996. };
  45997. Analyser.prototype.getFloatFrequencyData = function () {
  45998. if (this._audioEngine.canUseWebAudio) {
  45999. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46000. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46001. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  46002. }
  46003. return this._floatFreqs;
  46004. };
  46005. Analyser.prototype.drawDebugCanvas = function () {
  46006. var _this = this;
  46007. if (this._audioEngine.canUseWebAudio) {
  46008. if (!this._debugCanvas) {
  46009. this._debugCanvas = document.createElement("canvas");
  46010. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  46011. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  46012. this._debugCanvas.style.position = "absolute";
  46013. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  46014. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  46015. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  46016. document.body.appendChild(this._debugCanvas);
  46017. this._registerFunc = function () {
  46018. _this.drawDebugCanvas();
  46019. };
  46020. this._scene.registerBeforeRender(this._registerFunc);
  46021. }
  46022. if (this._registerFunc) {
  46023. var workingArray = this.getByteFrequencyData();
  46024. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  46025. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  46026. // Draw the frequency domain chart.
  46027. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  46028. var value = workingArray[i];
  46029. var percent = value / this.BARGRAPHAMPLITUDE;
  46030. var height = this.DEBUGCANVASSIZE.height * percent;
  46031. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  46032. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  46033. var hue = i / this.getFrequencyBinCount() * 360;
  46034. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  46035. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  46036. }
  46037. }
  46038. }
  46039. };
  46040. Analyser.prototype.stopDebugCanvas = function () {
  46041. if (this._debugCanvas) {
  46042. this._scene.unregisterBeforeRender(this._registerFunc);
  46043. this._registerFunc = null;
  46044. document.body.removeChild(this._debugCanvas);
  46045. this._debugCanvas = null;
  46046. this._debugCanvasContext = null;
  46047. }
  46048. };
  46049. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  46050. if (this._audioEngine.canUseWebAudio) {
  46051. inputAudioNode.connect(this._webAudioAnalyser);
  46052. this._webAudioAnalyser.connect(outputAudioNode);
  46053. }
  46054. };
  46055. Analyser.prototype.dispose = function () {
  46056. if (this._audioEngine.canUseWebAudio) {
  46057. this._webAudioAnalyser.disconnect();
  46058. }
  46059. };
  46060. return Analyser;
  46061. }());
  46062. BABYLON.Analyser = Analyser;
  46063. })(BABYLON || (BABYLON = {}));
  46064. //# sourceMappingURL=babylon.analyser.js.map
  46065. var BABYLON;
  46066. (function (BABYLON) {
  46067. var CubeTexture = (function (_super) {
  46068. __extends(CubeTexture, _super);
  46069. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  46070. if (onLoad === void 0) { onLoad = null; }
  46071. if (onError === void 0) { onError = null; }
  46072. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  46073. if (prefiltered === void 0) { prefiltered = false; }
  46074. if (forcedExtension === void 0) { forcedExtension = null; }
  46075. var _this = _super.call(this, scene) || this;
  46076. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  46077. _this.name = rootUrl;
  46078. _this.url = rootUrl;
  46079. _this._noMipmap = noMipmap;
  46080. _this.hasAlpha = false;
  46081. _this._format = format;
  46082. _this._prefiltered = prefiltered;
  46083. _this.isCube = true;
  46084. _this._textureMatrix = BABYLON.Matrix.Identity();
  46085. if (prefiltered) {
  46086. _this.gammaSpace = false;
  46087. }
  46088. if (!rootUrl && !files) {
  46089. return _this;
  46090. }
  46091. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  46092. if (!files) {
  46093. if (!extensions) {
  46094. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  46095. }
  46096. files = [];
  46097. for (var index = 0; index < extensions.length; index++) {
  46098. files.push(rootUrl + extensions[index]);
  46099. }
  46100. _this._extensions = extensions;
  46101. }
  46102. _this._files = files;
  46103. if (!_this._texture) {
  46104. if (!scene.useDelayedTextureLoading) {
  46105. if (prefiltered) {
  46106. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  46107. }
  46108. else {
  46109. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  46110. }
  46111. }
  46112. else {
  46113. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  46114. }
  46115. }
  46116. else if (onLoad) {
  46117. if (_this._texture.isReady) {
  46118. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  46119. }
  46120. else {
  46121. _this._texture.onLoadedObservable.add(onLoad);
  46122. }
  46123. }
  46124. return _this;
  46125. }
  46126. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  46127. return new CubeTexture("", scene, null, noMipmap, files);
  46128. };
  46129. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  46130. if (forcedExtension === void 0) { forcedExtension = null; }
  46131. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  46132. };
  46133. // Methods
  46134. CubeTexture.prototype.delayLoad = function () {
  46135. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  46136. return;
  46137. }
  46138. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  46139. this._texture = this._getFromCache(this.url, this._noMipmap);
  46140. if (!this._texture) {
  46141. if (this._prefiltered) {
  46142. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  46143. }
  46144. else {
  46145. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  46146. }
  46147. }
  46148. };
  46149. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  46150. return this._textureMatrix;
  46151. };
  46152. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  46153. this._textureMatrix = value;
  46154. };
  46155. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  46156. var texture = BABYLON.SerializationHelper.Parse(function () {
  46157. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  46158. }, parsedTexture, scene);
  46159. // Animations
  46160. if (parsedTexture.animations) {
  46161. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  46162. var parsedAnimation = parsedTexture.animations[animationIndex];
  46163. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  46164. }
  46165. }
  46166. return texture;
  46167. };
  46168. CubeTexture.prototype.clone = function () {
  46169. var _this = this;
  46170. return BABYLON.SerializationHelper.Clone(function () {
  46171. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  46172. }, this);
  46173. };
  46174. return CubeTexture;
  46175. }(BABYLON.BaseTexture));
  46176. BABYLON.CubeTexture = CubeTexture;
  46177. })(BABYLON || (BABYLON = {}));
  46178. //# sourceMappingURL=babylon.cubeTexture.js.map
  46179. var BABYLON;
  46180. (function (BABYLON) {
  46181. var RenderTargetTexture = (function (_super) {
  46182. __extends(RenderTargetTexture, _super);
  46183. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  46184. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  46185. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46186. if (isCube === void 0) { isCube = false; }
  46187. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46188. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  46189. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  46190. if (isMulti === void 0) { isMulti = false; }
  46191. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  46192. _this.isCube = isCube;
  46193. /**
  46194. * Use this list to define the list of mesh you want to render.
  46195. */
  46196. _this.renderList = new Array();
  46197. _this.renderParticles = true;
  46198. _this.renderSprites = false;
  46199. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  46200. _this.ignoreCameraViewport = false;
  46201. // Events
  46202. /**
  46203. * An event triggered when the texture is unbind.
  46204. * @type {BABYLON.Observable}
  46205. */
  46206. _this.onBeforeBindObservable = new BABYLON.Observable();
  46207. /**
  46208. * An event triggered when the texture is unbind.
  46209. * @type {BABYLON.Observable}
  46210. */
  46211. _this.onAfterUnbindObservable = new BABYLON.Observable();
  46212. /**
  46213. * An event triggered before rendering the texture
  46214. * @type {BABYLON.Observable}
  46215. */
  46216. _this.onBeforeRenderObservable = new BABYLON.Observable();
  46217. /**
  46218. * An event triggered after rendering the texture
  46219. * @type {BABYLON.Observable}
  46220. */
  46221. _this.onAfterRenderObservable = new BABYLON.Observable();
  46222. /**
  46223. * An event triggered after the texture clear
  46224. * @type {BABYLON.Observable}
  46225. */
  46226. _this.onClearObservable = new BABYLON.Observable();
  46227. _this._currentRefreshId = -1;
  46228. _this._refreshRate = 1;
  46229. _this._samples = 1;
  46230. scene = _this.getScene();
  46231. _this.name = name;
  46232. _this.isRenderTarget = true;
  46233. _this._size = size;
  46234. _this._generateMipMaps = generateMipMaps;
  46235. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  46236. // Rendering groups
  46237. _this._renderingManager = new BABYLON.RenderingManager(scene);
  46238. if (isMulti) {
  46239. return _this;
  46240. }
  46241. _this._renderTargetOptions = {
  46242. generateMipMaps: generateMipMaps,
  46243. type: type,
  46244. samplingMode: samplingMode,
  46245. generateDepthBuffer: generateDepthBuffer,
  46246. generateStencilBuffer: generateStencilBuffer
  46247. };
  46248. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  46249. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46250. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46251. }
  46252. if (isCube) {
  46253. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  46254. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  46255. _this._textureMatrix = BABYLON.Matrix.Identity();
  46256. }
  46257. else {
  46258. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  46259. }
  46260. return _this;
  46261. }
  46262. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  46263. get: function () {
  46264. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  46265. },
  46266. enumerable: true,
  46267. configurable: true
  46268. });
  46269. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  46270. get: function () {
  46271. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  46272. },
  46273. enumerable: true,
  46274. configurable: true
  46275. });
  46276. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  46277. get: function () {
  46278. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  46279. },
  46280. enumerable: true,
  46281. configurable: true
  46282. });
  46283. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  46284. set: function (callback) {
  46285. if (this._onAfterUnbindObserver) {
  46286. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  46287. }
  46288. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  46289. },
  46290. enumerable: true,
  46291. configurable: true
  46292. });
  46293. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  46294. set: function (callback) {
  46295. if (this._onBeforeRenderObserver) {
  46296. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  46297. }
  46298. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  46299. },
  46300. enumerable: true,
  46301. configurable: true
  46302. });
  46303. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  46304. set: function (callback) {
  46305. if (this._onAfterRenderObserver) {
  46306. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  46307. }
  46308. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  46309. },
  46310. enumerable: true,
  46311. configurable: true
  46312. });
  46313. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  46314. set: function (callback) {
  46315. if (this._onClearObserver) {
  46316. this.onClearObservable.remove(this._onClearObserver);
  46317. }
  46318. this._onClearObserver = this.onClearObservable.add(callback);
  46319. },
  46320. enumerable: true,
  46321. configurable: true
  46322. });
  46323. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  46324. get: function () {
  46325. return this._renderTargetOptions;
  46326. },
  46327. enumerable: true,
  46328. configurable: true
  46329. });
  46330. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  46331. get: function () {
  46332. return this._samples;
  46333. },
  46334. set: function (value) {
  46335. if (this._samples === value) {
  46336. return;
  46337. }
  46338. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  46339. },
  46340. enumerable: true,
  46341. configurable: true
  46342. });
  46343. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  46344. this._currentRefreshId = -1;
  46345. };
  46346. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  46347. get: function () {
  46348. return this._refreshRate;
  46349. },
  46350. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  46351. set: function (value) {
  46352. this._refreshRate = value;
  46353. this.resetRefreshCounter();
  46354. },
  46355. enumerable: true,
  46356. configurable: true
  46357. });
  46358. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  46359. if (!this._postProcessManager) {
  46360. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  46361. this._postProcesses = new Array();
  46362. }
  46363. this._postProcesses.push(postProcess);
  46364. this._postProcesses[0].autoClear = false;
  46365. };
  46366. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  46367. if (!this._postProcesses) {
  46368. return;
  46369. }
  46370. if (dispose) {
  46371. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  46372. var postProcess = _a[_i];
  46373. postProcess.dispose();
  46374. postProcess = null;
  46375. }
  46376. }
  46377. this._postProcesses = [];
  46378. };
  46379. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  46380. if (!this._postProcesses) {
  46381. return;
  46382. }
  46383. var index = this._postProcesses.indexOf(postProcess);
  46384. if (index === -1) {
  46385. return;
  46386. }
  46387. this._postProcesses.splice(index, 1);
  46388. if (this._postProcesses.length > 0) {
  46389. this._postProcesses[0].autoClear = false;
  46390. }
  46391. };
  46392. RenderTargetTexture.prototype._shouldRender = function () {
  46393. if (this._currentRefreshId === -1) {
  46394. this._currentRefreshId = 1;
  46395. return true;
  46396. }
  46397. if (this.refreshRate === this._currentRefreshId) {
  46398. this._currentRefreshId = 1;
  46399. return true;
  46400. }
  46401. this._currentRefreshId++;
  46402. return false;
  46403. };
  46404. RenderTargetTexture.prototype.getRenderSize = function () {
  46405. return this._size;
  46406. };
  46407. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  46408. get: function () {
  46409. return true;
  46410. },
  46411. enumerable: true,
  46412. configurable: true
  46413. });
  46414. RenderTargetTexture.prototype.scale = function (ratio) {
  46415. var newSize = this._size * ratio;
  46416. this.resize(newSize);
  46417. };
  46418. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  46419. if (this.isCube) {
  46420. return this._textureMatrix;
  46421. }
  46422. return _super.prototype.getReflectionTextureMatrix.call(this);
  46423. };
  46424. RenderTargetTexture.prototype.resize = function (size) {
  46425. this.releaseInternalTexture();
  46426. if (this.isCube) {
  46427. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  46428. }
  46429. else {
  46430. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  46431. }
  46432. this._size = size;
  46433. };
  46434. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  46435. var scene = this.getScene();
  46436. var engine = scene.getEngine();
  46437. if (this.useCameraPostProcesses !== undefined) {
  46438. useCameraPostProcess = this.useCameraPostProcesses;
  46439. }
  46440. if (this._waitingRenderList) {
  46441. this.renderList = [];
  46442. for (var index = 0; index < this._waitingRenderList.length; index++) {
  46443. var id = this._waitingRenderList[index];
  46444. this.renderList.push(scene.getMeshByID(id));
  46445. }
  46446. delete this._waitingRenderList;
  46447. }
  46448. // Is predicate defined?
  46449. if (this.renderListPredicate) {
  46450. this.renderList.splice(0); // Clear previous renderList
  46451. var sceneMeshes = this.getScene().meshes;
  46452. for (var index = 0; index < sceneMeshes.length; index++) {
  46453. var mesh = sceneMeshes[index];
  46454. if (this.renderListPredicate(mesh)) {
  46455. this.renderList.push(mesh);
  46456. }
  46457. }
  46458. }
  46459. if (this.renderList && this.renderList.length === 0) {
  46460. return;
  46461. }
  46462. this.onBeforeBindObservable.notifyObservers(this);
  46463. // Set custom projection.
  46464. // Needs to be before binding to prevent changing the aspect ratio.
  46465. var camera;
  46466. if (this.activeCamera) {
  46467. camera = this.activeCamera;
  46468. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  46469. if (this.activeCamera !== scene.activeCamera) {
  46470. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  46471. }
  46472. }
  46473. else {
  46474. camera = scene.activeCamera;
  46475. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  46476. }
  46477. // Prepare renderingManager
  46478. this._renderingManager.reset();
  46479. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  46480. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  46481. var sceneRenderId = scene.getRenderId();
  46482. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  46483. var mesh = currentRenderList[meshIndex];
  46484. if (mesh) {
  46485. if (!mesh.isReady()) {
  46486. // Reset _currentRefreshId
  46487. this.resetRefreshCounter();
  46488. continue;
  46489. }
  46490. mesh._preActivateForIntermediateRendering(sceneRenderId);
  46491. var isMasked = void 0;
  46492. if (!this.renderList) {
  46493. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  46494. }
  46495. else {
  46496. isMasked = false;
  46497. }
  46498. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  46499. mesh._activate(sceneRenderId);
  46500. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  46501. var subMesh = mesh.subMeshes[subIndex];
  46502. scene._activeIndices.addCount(subMesh.indexCount, false);
  46503. this._renderingManager.dispatch(subMesh);
  46504. }
  46505. }
  46506. }
  46507. }
  46508. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  46509. var particleSystem = scene.particleSystems[particleIndex];
  46510. var emitter = particleSystem.emitter;
  46511. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  46512. continue;
  46513. }
  46514. if (currentRenderList.indexOf(emitter) >= 0) {
  46515. this._renderingManager.dispatchParticles(particleSystem);
  46516. }
  46517. }
  46518. if (this.isCube) {
  46519. for (var face = 0; face < 6; face++) {
  46520. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  46521. scene.incrementRenderId();
  46522. scene.resetCachedMaterial();
  46523. }
  46524. }
  46525. else {
  46526. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  46527. }
  46528. this.onAfterUnbindObservable.notifyObservers(this);
  46529. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  46530. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  46531. }
  46532. engine.setViewport(scene.activeCamera.viewport);
  46533. scene.resetCachedMaterial();
  46534. };
  46535. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  46536. var _this = this;
  46537. var scene = this.getScene();
  46538. var engine = scene.getEngine();
  46539. // Bind
  46540. if (this._postProcessManager) {
  46541. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  46542. }
  46543. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  46544. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  46545. }
  46546. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  46547. // Clear
  46548. if (this.onClearObservable.hasObservers()) {
  46549. this.onClearObservable.notifyObservers(engine);
  46550. }
  46551. else {
  46552. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  46553. }
  46554. if (!this._doNotChangeAspectRatio) {
  46555. scene.updateTransformMatrix(true);
  46556. }
  46557. // Render
  46558. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  46559. if (this._postProcessManager) {
  46560. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  46561. }
  46562. else if (useCameraPostProcess) {
  46563. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  46564. }
  46565. if (!this._doNotChangeAspectRatio) {
  46566. scene.updateTransformMatrix(true);
  46567. }
  46568. // Dump ?
  46569. if (dumpForDebug) {
  46570. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  46571. }
  46572. // Unbind
  46573. if (!this.isCube || faceIndex === 5) {
  46574. if (this.isCube) {
  46575. if (faceIndex === 5) {
  46576. engine.generateMipMapsForCubemap(this._texture);
  46577. }
  46578. }
  46579. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  46580. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  46581. });
  46582. }
  46583. else {
  46584. this.onAfterRenderObservable.notifyObservers(faceIndex);
  46585. }
  46586. };
  46587. /**
  46588. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  46589. * This allowed control for front to back rendering or reversly depending of the special needs.
  46590. *
  46591. * @param renderingGroupId The rendering group id corresponding to its index
  46592. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  46593. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  46594. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  46595. */
  46596. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  46597. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  46598. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  46599. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  46600. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  46601. };
  46602. /**
  46603. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  46604. *
  46605. * @param renderingGroupId The rendering group id corresponding to its index
  46606. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  46607. */
  46608. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  46609. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  46610. };
  46611. RenderTargetTexture.prototype.clone = function () {
  46612. var textureSize = this.getSize();
  46613. 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);
  46614. // Base texture
  46615. newTexture.hasAlpha = this.hasAlpha;
  46616. newTexture.level = this.level;
  46617. // RenderTarget Texture
  46618. newTexture.coordinatesMode = this.coordinatesMode;
  46619. newTexture.renderList = this.renderList.slice(0);
  46620. return newTexture;
  46621. };
  46622. RenderTargetTexture.prototype.serialize = function () {
  46623. if (!this.name) {
  46624. return null;
  46625. }
  46626. var serializationObject = _super.prototype.serialize.call(this);
  46627. serializationObject.renderTargetSize = this.getRenderSize();
  46628. serializationObject.renderList = [];
  46629. for (var index = 0; index < this.renderList.length; index++) {
  46630. serializationObject.renderList.push(this.renderList[index].id);
  46631. }
  46632. return serializationObject;
  46633. };
  46634. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  46635. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  46636. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  46637. };
  46638. RenderTargetTexture.prototype.dispose = function () {
  46639. if (this._postProcessManager) {
  46640. this._postProcessManager.dispose();
  46641. this._postProcessManager = null;
  46642. }
  46643. this.clearPostProcesses(true);
  46644. this.renderList = null;
  46645. // Remove from custom render targets
  46646. var scene = this.getScene();
  46647. var index = scene.customRenderTargets.indexOf(this);
  46648. if (index >= 0) {
  46649. scene.customRenderTargets.splice(index, 1);
  46650. }
  46651. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  46652. var camera = _a[_i];
  46653. index = camera.customRenderTargets.indexOf(this);
  46654. if (index >= 0) {
  46655. camera.customRenderTargets.splice(index, 1);
  46656. }
  46657. }
  46658. _super.prototype.dispose.call(this);
  46659. };
  46660. RenderTargetTexture.prototype._rebuild = function () {
  46661. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  46662. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  46663. }
  46664. if (this._postProcessManager) {
  46665. this._postProcessManager._rebuild();
  46666. }
  46667. };
  46668. return RenderTargetTexture;
  46669. }(BABYLON.Texture));
  46670. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  46671. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  46672. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  46673. BABYLON.RenderTargetTexture = RenderTargetTexture;
  46674. })(BABYLON || (BABYLON = {}));
  46675. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  46676. var BABYLON;
  46677. (function (BABYLON) {
  46678. ;
  46679. var MultiRenderTarget = (function (_super) {
  46680. __extends(MultiRenderTarget, _super);
  46681. function MultiRenderTarget(name, size, count, scene, options) {
  46682. var _this = this;
  46683. options = options || {};
  46684. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  46685. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  46686. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  46687. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  46688. if (!_this.isSupported) {
  46689. _this.dispose();
  46690. return;
  46691. }
  46692. var types = [];
  46693. var samplingModes = [];
  46694. for (var i = 0; i < count; i++) {
  46695. if (options.types && options.types[i]) {
  46696. types.push(options.types[i]);
  46697. }
  46698. else {
  46699. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  46700. }
  46701. if (options.samplingModes && options.samplingModes[i]) {
  46702. samplingModes.push(options.samplingModes[i]);
  46703. }
  46704. else {
  46705. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46706. }
  46707. }
  46708. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  46709. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  46710. _this._count = count;
  46711. _this._size = size;
  46712. _this._multiRenderTargetOptions = {
  46713. samplingModes: samplingModes,
  46714. generateMipMaps: generateMipMaps,
  46715. generateDepthBuffer: generateDepthBuffer,
  46716. generateStencilBuffer: generateStencilBuffer,
  46717. generateDepthTexture: generateDepthTexture,
  46718. types: types,
  46719. textureCount: count
  46720. };
  46721. _this._createInternalTextures();
  46722. _this._createTextures();
  46723. return _this;
  46724. }
  46725. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  46726. get: function () {
  46727. var engine = this.getScene().getEngine();
  46728. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  46729. },
  46730. enumerable: true,
  46731. configurable: true
  46732. });
  46733. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  46734. get: function () {
  46735. return this._textures;
  46736. },
  46737. enumerable: true,
  46738. configurable: true
  46739. });
  46740. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  46741. get: function () {
  46742. return this._textures[this._textures.length - 1];
  46743. },
  46744. enumerable: true,
  46745. configurable: true
  46746. });
  46747. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  46748. set: function (wrap) {
  46749. if (this._textures) {
  46750. for (var i = 0; i < this._textures.length; i++) {
  46751. this._textures[i].wrapU = wrap;
  46752. }
  46753. }
  46754. },
  46755. enumerable: true,
  46756. configurable: true
  46757. });
  46758. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  46759. set: function (wrap) {
  46760. if (this._textures) {
  46761. for (var i = 0; i < this._textures.length; i++) {
  46762. this._textures[i].wrapV = wrap;
  46763. }
  46764. }
  46765. },
  46766. enumerable: true,
  46767. configurable: true
  46768. });
  46769. MultiRenderTarget.prototype._rebuild = function () {
  46770. this.releaseInternalTextures();
  46771. this._createInternalTextures();
  46772. for (var i = 0; i < this._internalTextures.length; i++) {
  46773. var texture = this._textures[i];
  46774. texture._texture = this._internalTextures[i];
  46775. }
  46776. // Keeps references to frame buffer and stencil/depth buffer
  46777. this._texture = this._internalTextures[0];
  46778. };
  46779. MultiRenderTarget.prototype._createInternalTextures = function () {
  46780. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  46781. };
  46782. MultiRenderTarget.prototype._createTextures = function () {
  46783. this._textures = [];
  46784. for (var i = 0; i < this._internalTextures.length; i++) {
  46785. var texture = new BABYLON.Texture(null, this.getScene());
  46786. texture._texture = this._internalTextures[i];
  46787. this._textures.push(texture);
  46788. }
  46789. // Keeps references to frame buffer and stencil/depth buffer
  46790. this._texture = this._internalTextures[0];
  46791. };
  46792. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  46793. get: function () {
  46794. return this._samples;
  46795. },
  46796. set: function (value) {
  46797. if (this._samples === value) {
  46798. return;
  46799. }
  46800. for (var i = 0; i < this._internalTextures.length; i++) {
  46801. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  46802. }
  46803. },
  46804. enumerable: true,
  46805. configurable: true
  46806. });
  46807. MultiRenderTarget.prototype.resize = function (size) {
  46808. this.releaseInternalTextures();
  46809. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  46810. this._createInternalTextures();
  46811. };
  46812. MultiRenderTarget.prototype.dispose = function () {
  46813. this.releaseInternalTextures();
  46814. _super.prototype.dispose.call(this);
  46815. };
  46816. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  46817. if (!this._internalTextures) {
  46818. return;
  46819. }
  46820. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  46821. if (this._internalTextures[i] !== undefined) {
  46822. this._internalTextures[i].dispose();
  46823. this._internalTextures.splice(i, 1);
  46824. }
  46825. }
  46826. };
  46827. return MultiRenderTarget;
  46828. }(BABYLON.RenderTargetTexture));
  46829. BABYLON.MultiRenderTarget = MultiRenderTarget;
  46830. })(BABYLON || (BABYLON = {}));
  46831. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  46832. /// <reference path="babylon.renderTargetTexture.ts" />
  46833. var BABYLON;
  46834. (function (BABYLON) {
  46835. var MirrorTexture = (function (_super) {
  46836. __extends(MirrorTexture, _super);
  46837. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  46838. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46839. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46840. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  46841. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  46842. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  46843. _this._transformMatrix = BABYLON.Matrix.Zero();
  46844. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  46845. _this._blurKernelX = 0;
  46846. _this._blurKernelY = 0;
  46847. _this._blurRatio = 1.0;
  46848. _this.ignoreCameraViewport = true;
  46849. _this.onBeforeRenderObservable.add(function () {
  46850. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  46851. _this._savedViewMatrix = scene.getViewMatrix();
  46852. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  46853. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  46854. scene.clipPlane = _this.mirrorPlane;
  46855. scene.getEngine().cullBackFaces = false;
  46856. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  46857. });
  46858. _this.onAfterRenderObservable.add(function () {
  46859. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  46860. scene.getEngine().cullBackFaces = true;
  46861. scene._mirroredCameraPosition = null;
  46862. delete scene.clipPlane;
  46863. });
  46864. return _this;
  46865. }
  46866. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  46867. get: function () {
  46868. return this._blurRatio;
  46869. },
  46870. set: function (value) {
  46871. if (this._blurRatio === value) {
  46872. return;
  46873. }
  46874. this._blurRatio = value;
  46875. this._preparePostProcesses();
  46876. },
  46877. enumerable: true,
  46878. configurable: true
  46879. });
  46880. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  46881. set: function (value) {
  46882. this.blurKernelX = value;
  46883. this.blurKernelY = value;
  46884. },
  46885. enumerable: true,
  46886. configurable: true
  46887. });
  46888. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  46889. get: function () {
  46890. return this._blurKernelX;
  46891. },
  46892. set: function (value) {
  46893. if (this._blurKernelX === value) {
  46894. return;
  46895. }
  46896. this._blurKernelX = value;
  46897. this._preparePostProcesses();
  46898. },
  46899. enumerable: true,
  46900. configurable: true
  46901. });
  46902. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  46903. get: function () {
  46904. return this._blurKernelY;
  46905. },
  46906. set: function (value) {
  46907. if (this._blurKernelY === value) {
  46908. return;
  46909. }
  46910. this._blurKernelY = value;
  46911. this._preparePostProcesses();
  46912. },
  46913. enumerable: true,
  46914. configurable: true
  46915. });
  46916. MirrorTexture.prototype._preparePostProcesses = function () {
  46917. this.clearPostProcesses(true);
  46918. if (this._blurKernelX && this._blurKernelY) {
  46919. var engine = this.getScene().getEngine();
  46920. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  46921. 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);
  46922. this._blurX.autoClear = false;
  46923. if (this._blurRatio === 1 && this.samples < 2) {
  46924. this._blurX.outputTexture = this._texture;
  46925. }
  46926. else {
  46927. this._blurX.alwaysForcePOT = true;
  46928. }
  46929. 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);
  46930. this._blurY.autoClear = false;
  46931. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  46932. this.addPostProcess(this._blurX);
  46933. this.addPostProcess(this._blurY);
  46934. }
  46935. };
  46936. MirrorTexture.prototype.clone = function () {
  46937. var textureSize = this.getSize();
  46938. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  46939. // Base texture
  46940. newTexture.hasAlpha = this.hasAlpha;
  46941. newTexture.level = this.level;
  46942. // Mirror Texture
  46943. newTexture.mirrorPlane = this.mirrorPlane.clone();
  46944. newTexture.renderList = this.renderList.slice(0);
  46945. return newTexture;
  46946. };
  46947. MirrorTexture.prototype.serialize = function () {
  46948. if (!this.name) {
  46949. return null;
  46950. }
  46951. var serializationObject = _super.prototype.serialize.call(this);
  46952. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  46953. return serializationObject;
  46954. };
  46955. return MirrorTexture;
  46956. }(BABYLON.RenderTargetTexture));
  46957. BABYLON.MirrorTexture = MirrorTexture;
  46958. })(BABYLON || (BABYLON = {}));
  46959. //# sourceMappingURL=babylon.mirrorTexture.js.map
  46960. /// <reference path="babylon.renderTargetTexture.ts" />
  46961. var BABYLON;
  46962. (function (BABYLON) {
  46963. /**
  46964. * Creates a refraction texture used by refraction channel of the standard material.
  46965. * @param name the texture name
  46966. * @param size size of the underlying texture
  46967. * @param scene root scene
  46968. */
  46969. var RefractionTexture = (function (_super) {
  46970. __extends(RefractionTexture, _super);
  46971. function RefractionTexture(name, size, scene, generateMipMaps) {
  46972. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  46973. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  46974. _this.depth = 2.0;
  46975. _this.onBeforeRenderObservable.add(function () {
  46976. scene.clipPlane = _this.refractionPlane;
  46977. });
  46978. _this.onAfterRenderObservable.add(function () {
  46979. delete scene.clipPlane;
  46980. });
  46981. return _this;
  46982. }
  46983. RefractionTexture.prototype.clone = function () {
  46984. var textureSize = this.getSize();
  46985. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  46986. // Base texture
  46987. newTexture.hasAlpha = this.hasAlpha;
  46988. newTexture.level = this.level;
  46989. // Refraction Texture
  46990. newTexture.refractionPlane = this.refractionPlane.clone();
  46991. newTexture.renderList = this.renderList.slice(0);
  46992. newTexture.depth = this.depth;
  46993. return newTexture;
  46994. };
  46995. RefractionTexture.prototype.serialize = function () {
  46996. if (!this.name) {
  46997. return null;
  46998. }
  46999. var serializationObject = _super.prototype.serialize.call(this);
  47000. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  47001. serializationObject.depth = this.depth;
  47002. return serializationObject;
  47003. };
  47004. return RefractionTexture;
  47005. }(BABYLON.RenderTargetTexture));
  47006. BABYLON.RefractionTexture = RefractionTexture;
  47007. })(BABYLON || (BABYLON = {}));
  47008. //# sourceMappingURL=babylon.refractionTexture.js.map
  47009. /// <reference path="babylon.texture.ts" />
  47010. var BABYLON;
  47011. (function (BABYLON) {
  47012. var DynamicTexture = (function (_super) {
  47013. __extends(DynamicTexture, _super);
  47014. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  47015. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47016. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  47017. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  47018. _this.name = name;
  47019. var engine = _this.getScene().getEngine();
  47020. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47021. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47022. _this._generateMipMaps = generateMipMaps;
  47023. if (options.getContext) {
  47024. _this._canvas = options;
  47025. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  47026. }
  47027. else {
  47028. _this._canvas = document.createElement("canvas");
  47029. if (options.width) {
  47030. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  47031. }
  47032. else {
  47033. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  47034. }
  47035. }
  47036. var textureSize = _this.getSize();
  47037. _this._canvas.width = textureSize.width;
  47038. _this._canvas.height = textureSize.height;
  47039. _this._context = _this._canvas.getContext("2d");
  47040. return _this;
  47041. }
  47042. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  47043. get: function () {
  47044. return true;
  47045. },
  47046. enumerable: true,
  47047. configurable: true
  47048. });
  47049. DynamicTexture.prototype._recreate = function (textureSize) {
  47050. this._canvas.width = textureSize.width;
  47051. this._canvas.height = textureSize.height;
  47052. this.releaseInternalTexture();
  47053. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  47054. };
  47055. DynamicTexture.prototype.scale = function (ratio) {
  47056. var textureSize = this.getSize();
  47057. textureSize.width *= ratio;
  47058. textureSize.height *= ratio;
  47059. this._recreate(textureSize);
  47060. };
  47061. DynamicTexture.prototype.scaleTo = function (width, height) {
  47062. var textureSize = this.getSize();
  47063. textureSize.width = width;
  47064. textureSize.height = height;
  47065. this._recreate(textureSize);
  47066. };
  47067. DynamicTexture.prototype.getContext = function () {
  47068. return this._context;
  47069. };
  47070. DynamicTexture.prototype.clear = function () {
  47071. var size = this.getSize();
  47072. this._context.fillRect(0, 0, size.width, size.height);
  47073. };
  47074. DynamicTexture.prototype.update = function (invertY) {
  47075. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  47076. };
  47077. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  47078. if (update === void 0) { update = true; }
  47079. var size = this.getSize();
  47080. if (clearColor) {
  47081. this._context.fillStyle = clearColor;
  47082. this._context.fillRect(0, 0, size.width, size.height);
  47083. }
  47084. this._context.font = font;
  47085. if (x === null || x === undefined) {
  47086. var textSize = this._context.measureText(text);
  47087. x = (size.width - textSize.width) / 2;
  47088. }
  47089. if (y === null || y === undefined) {
  47090. var fontSize = parseInt((font.replace(/\D/g, '')));
  47091. ;
  47092. y = (size.height / 2) + (fontSize / 3.65);
  47093. }
  47094. this._context.fillStyle = color;
  47095. this._context.fillText(text, x, y);
  47096. if (update) {
  47097. this.update(invertY);
  47098. }
  47099. };
  47100. DynamicTexture.prototype.clone = function () {
  47101. var textureSize = this.getSize();
  47102. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  47103. // Base texture
  47104. newTexture.hasAlpha = this.hasAlpha;
  47105. newTexture.level = this.level;
  47106. // Dynamic Texture
  47107. newTexture.wrapU = this.wrapU;
  47108. newTexture.wrapV = this.wrapV;
  47109. return newTexture;
  47110. };
  47111. DynamicTexture.prototype._rebuild = function () {
  47112. this.update();
  47113. };
  47114. return DynamicTexture;
  47115. }(BABYLON.Texture));
  47116. BABYLON.DynamicTexture = DynamicTexture;
  47117. })(BABYLON || (BABYLON = {}));
  47118. //# sourceMappingURL=babylon.dynamicTexture.js.map
  47119. var BABYLON;
  47120. (function (BABYLON) {
  47121. var VideoTexture = (function (_super) {
  47122. __extends(VideoTexture, _super);
  47123. /**
  47124. * Creates a video texture.
  47125. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  47126. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  47127. * @param {BABYLON.Scene} scene is obviously the current scene.
  47128. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  47129. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  47130. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  47131. */
  47132. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  47133. if (generateMipMaps === void 0) { generateMipMaps = false; }
  47134. if (invertY === void 0) { invertY = false; }
  47135. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47136. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  47137. _this._autoLaunch = true;
  47138. var urls;
  47139. _this.name = name;
  47140. if (urlsOrVideo instanceof HTMLVideoElement) {
  47141. _this.video = urlsOrVideo;
  47142. }
  47143. else {
  47144. urls = urlsOrVideo;
  47145. _this.video = document.createElement("video");
  47146. _this.video.autoplay = false;
  47147. _this.video.loop = true;
  47148. }
  47149. _this._generateMipMaps = generateMipMaps;
  47150. _this._samplingMode = samplingMode;
  47151. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  47152. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47153. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47154. }
  47155. else {
  47156. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47157. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47158. _this._generateMipMaps = false;
  47159. }
  47160. if (urls) {
  47161. _this.video.addEventListener("canplay", function () {
  47162. _this._createTexture();
  47163. });
  47164. urls.forEach(function (url) {
  47165. var source = document.createElement("source");
  47166. source.src = url;
  47167. _this.video.appendChild(source);
  47168. });
  47169. }
  47170. else {
  47171. _this._createTexture();
  47172. }
  47173. _this._lastUpdate = BABYLON.Tools.Now;
  47174. return _this;
  47175. }
  47176. VideoTexture.prototype.__setTextureReady = function () {
  47177. this._texture.isReady = true;
  47178. };
  47179. VideoTexture.prototype._createTexture = function () {
  47180. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  47181. if (this._autoLaunch) {
  47182. this._autoLaunch = false;
  47183. this.video.play();
  47184. }
  47185. this._setTextureReady = this.__setTextureReady.bind(this);
  47186. this.video.addEventListener("playing", this._setTextureReady);
  47187. };
  47188. VideoTexture.prototype._rebuild = function () {
  47189. this.update();
  47190. };
  47191. VideoTexture.prototype.update = function () {
  47192. var now = BABYLON.Tools.Now;
  47193. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  47194. return false;
  47195. }
  47196. this._lastUpdate = now;
  47197. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  47198. return true;
  47199. };
  47200. VideoTexture.prototype.dispose = function () {
  47201. _super.prototype.dispose.call(this);
  47202. this.video.removeEventListener("playing", this._setTextureReady);
  47203. };
  47204. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  47205. var video = document.createElement("video");
  47206. var constraintsDeviceId;
  47207. if (constraints && constraints.deviceId) {
  47208. constraintsDeviceId = {
  47209. exact: constraints.deviceId
  47210. };
  47211. }
  47212. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  47213. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  47214. if (navigator.getUserMedia) {
  47215. navigator.getUserMedia({
  47216. video: {
  47217. deviceId: constraintsDeviceId,
  47218. width: {
  47219. min: (constraints && constraints.minWidth) || 256,
  47220. max: (constraints && constraints.maxWidth) || 640
  47221. },
  47222. height: {
  47223. min: (constraints && constraints.minHeight) || 256,
  47224. max: (constraints && constraints.maxHeight) || 480
  47225. }
  47226. }
  47227. }, function (stream) {
  47228. if (video.mozSrcObject !== undefined) {
  47229. video.mozSrcObject = stream;
  47230. }
  47231. else {
  47232. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  47233. }
  47234. video.play();
  47235. if (onReady) {
  47236. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  47237. }
  47238. }, function (e) {
  47239. BABYLON.Tools.Error(e.name);
  47240. });
  47241. }
  47242. };
  47243. return VideoTexture;
  47244. }(BABYLON.Texture));
  47245. BABYLON.VideoTexture = VideoTexture;
  47246. })(BABYLON || (BABYLON = {}));
  47247. //# sourceMappingURL=babylon.videoTexture.js.map
  47248. var BABYLON;
  47249. (function (BABYLON) {
  47250. var RawTexture = (function (_super) {
  47251. __extends(RawTexture, _super);
  47252. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  47253. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47254. if (invertY === void 0) { invertY = false; }
  47255. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47256. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  47257. _this.format = format;
  47258. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  47259. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47260. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47261. return _this;
  47262. }
  47263. RawTexture.prototype.update = function (data) {
  47264. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  47265. };
  47266. // Statics
  47267. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47268. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47269. if (invertY === void 0) { invertY = false; }
  47270. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47271. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  47272. };
  47273. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47274. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47275. if (invertY === void 0) { invertY = false; }
  47276. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47277. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  47278. };
  47279. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47280. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47281. if (invertY === void 0) { invertY = false; }
  47282. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47283. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  47284. };
  47285. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47286. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47287. if (invertY === void 0) { invertY = false; }
  47288. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47289. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  47290. };
  47291. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47292. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47293. if (invertY === void 0) { invertY = false; }
  47294. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47295. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  47296. };
  47297. return RawTexture;
  47298. }(BABYLON.Texture));
  47299. BABYLON.RawTexture = RawTexture;
  47300. })(BABYLON || (BABYLON = {}));
  47301. //# sourceMappingURL=babylon.rawTexture.js.map
  47302. var BABYLON;
  47303. (function (BABYLON) {
  47304. var PostProcess = (function () {
  47305. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  47306. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  47307. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47308. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  47309. if (blockCompilation === void 0) { blockCompilation = false; }
  47310. this.name = name;
  47311. this.width = -1;
  47312. this.height = -1;
  47313. this.autoClear = true;
  47314. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  47315. /*
  47316. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  47317. Can only be used on a single postprocess or on the last one of a chain.
  47318. */
  47319. this.enablePixelPerfectMode = false;
  47320. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  47321. this.alwaysForcePOT = false;
  47322. this.samples = 1;
  47323. this.adaptScaleToCurrentViewport = false;
  47324. this._reusable = false;
  47325. this._textures = new BABYLON.SmartArray(2);
  47326. this._currentRenderTextureInd = 0;
  47327. this._scaleRatio = new BABYLON.Vector2(1, 1);
  47328. this._texelSize = BABYLON.Vector2.Zero();
  47329. // Events
  47330. /**
  47331. * An event triggered when the postprocess is activated.
  47332. * @type {BABYLON.Observable}
  47333. */
  47334. this.onActivateObservable = new BABYLON.Observable();
  47335. /**
  47336. * An event triggered when the postprocess changes its size.
  47337. * @type {BABYLON.Observable}
  47338. */
  47339. this.onSizeChangedObservable = new BABYLON.Observable();
  47340. /**
  47341. * An event triggered when the postprocess applies its effect.
  47342. * @type {BABYLON.Observable}
  47343. */
  47344. this.onApplyObservable = new BABYLON.Observable();
  47345. /**
  47346. * An event triggered before rendering the postprocess
  47347. * @type {BABYLON.Observable}
  47348. */
  47349. this.onBeforeRenderObservable = new BABYLON.Observable();
  47350. /**
  47351. * An event triggered after rendering the postprocess
  47352. * @type {BABYLON.Observable}
  47353. */
  47354. this.onAfterRenderObservable = new BABYLON.Observable();
  47355. if (camera != null) {
  47356. this._camera = camera;
  47357. this._scene = camera.getScene();
  47358. camera.attachPostProcess(this);
  47359. this._engine = this._scene.getEngine();
  47360. this._scene.postProcesses.push(this);
  47361. }
  47362. else {
  47363. this._engine = engine;
  47364. this._engine.postProcesses.push(this);
  47365. }
  47366. this._options = options;
  47367. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  47368. this._reusable = reusable || false;
  47369. this._textureType = textureType;
  47370. this._samplers = samplers || [];
  47371. this._samplers.push("textureSampler");
  47372. this._fragmentUrl = fragmentUrl;
  47373. this._vertexUrl = vertexUrl;
  47374. this._parameters = parameters || [];
  47375. this._parameters.push("scale");
  47376. this._indexParameters = indexParameters;
  47377. if (!blockCompilation) {
  47378. this.updateEffect(defines);
  47379. }
  47380. }
  47381. Object.defineProperty(PostProcess.prototype, "onActivate", {
  47382. set: function (callback) {
  47383. if (this._onActivateObserver) {
  47384. this.onActivateObservable.remove(this._onActivateObserver);
  47385. }
  47386. this._onActivateObserver = this.onActivateObservable.add(callback);
  47387. },
  47388. enumerable: true,
  47389. configurable: true
  47390. });
  47391. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  47392. set: function (callback) {
  47393. if (this._onSizeChangedObserver) {
  47394. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  47395. }
  47396. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  47397. },
  47398. enumerable: true,
  47399. configurable: true
  47400. });
  47401. Object.defineProperty(PostProcess.prototype, "onApply", {
  47402. set: function (callback) {
  47403. if (this._onApplyObserver) {
  47404. this.onApplyObservable.remove(this._onApplyObserver);
  47405. }
  47406. this._onApplyObserver = this.onApplyObservable.add(callback);
  47407. },
  47408. enumerable: true,
  47409. configurable: true
  47410. });
  47411. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  47412. set: function (callback) {
  47413. if (this._onBeforeRenderObserver) {
  47414. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  47415. }
  47416. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  47417. },
  47418. enumerable: true,
  47419. configurable: true
  47420. });
  47421. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  47422. set: function (callback) {
  47423. if (this._onAfterRenderObserver) {
  47424. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  47425. }
  47426. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  47427. },
  47428. enumerable: true,
  47429. configurable: true
  47430. });
  47431. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  47432. get: function () {
  47433. return this._textures.data[this._currentRenderTextureInd];
  47434. },
  47435. set: function (value) {
  47436. this._forcedOutputTexture = value;
  47437. },
  47438. enumerable: true,
  47439. configurable: true
  47440. });
  47441. PostProcess.prototype.getCamera = function () {
  47442. return this._camera;
  47443. };
  47444. Object.defineProperty(PostProcess.prototype, "texelSize", {
  47445. get: function () {
  47446. if (this._shareOutputWithPostProcess) {
  47447. return this._shareOutputWithPostProcess.texelSize;
  47448. }
  47449. if (this._forcedOutputTexture) {
  47450. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  47451. }
  47452. return this._texelSize;
  47453. },
  47454. enumerable: true,
  47455. configurable: true
  47456. });
  47457. PostProcess.prototype.getEngine = function () {
  47458. return this._engine;
  47459. };
  47460. PostProcess.prototype.getEffect = function () {
  47461. return this._effect;
  47462. };
  47463. PostProcess.prototype.shareOutputWith = function (postProcess) {
  47464. this._disposeTextures();
  47465. this._shareOutputWithPostProcess = postProcess;
  47466. return this;
  47467. };
  47468. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  47469. 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);
  47470. };
  47471. PostProcess.prototype.isReusable = function () {
  47472. return this._reusable;
  47473. };
  47474. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  47475. PostProcess.prototype.markTextureDirty = function () {
  47476. this.width = -1;
  47477. };
  47478. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  47479. var _this = this;
  47480. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  47481. camera = camera || this._camera;
  47482. var scene = camera.getScene();
  47483. var engine = scene.getEngine();
  47484. var maxSize = engine.getCaps().maxTextureSize;
  47485. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  47486. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  47487. var desiredWidth = (this._options.width || requiredWidth);
  47488. var desiredHeight = this._options.height || requiredHeight;
  47489. if (this.adaptScaleToCurrentViewport) {
  47490. var currentViewport = engine.currentViewport;
  47491. if (currentViewport) {
  47492. desiredWidth *= currentViewport.width;
  47493. desiredHeight *= currentViewport.height;
  47494. }
  47495. }
  47496. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  47497. if (!this._options.width) {
  47498. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  47499. }
  47500. if (!this._options.height) {
  47501. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  47502. }
  47503. }
  47504. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  47505. if (this._textures.length > 0) {
  47506. for (var i = 0; i < this._textures.length; i++) {
  47507. this._engine._releaseTexture(this._textures.data[i]);
  47508. }
  47509. this._textures.reset();
  47510. }
  47511. this.width = desiredWidth;
  47512. this.height = desiredHeight;
  47513. var textureSize = { width: this.width, height: this.height };
  47514. var textureOptions = {
  47515. generateMipMaps: false,
  47516. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  47517. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  47518. samplingMode: this.renderTargetSamplingMode,
  47519. type: this._textureType
  47520. };
  47521. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  47522. if (this._reusable) {
  47523. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  47524. }
  47525. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  47526. this.onSizeChangedObservable.notifyObservers(this);
  47527. }
  47528. this._textures.forEach(function (texture) {
  47529. if (texture.samples !== _this.samples) {
  47530. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  47531. }
  47532. });
  47533. }
  47534. var target;
  47535. if (this._shareOutputWithPostProcess) {
  47536. target = this._shareOutputWithPostProcess.outputTexture;
  47537. }
  47538. else if (this._forcedOutputTexture) {
  47539. target = this._forcedOutputTexture;
  47540. this.width = this._forcedOutputTexture.width;
  47541. this.height = this._forcedOutputTexture.height;
  47542. }
  47543. else {
  47544. target = this.outputTexture;
  47545. }
  47546. if (this.enablePixelPerfectMode) {
  47547. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  47548. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  47549. }
  47550. else {
  47551. this._scaleRatio.copyFromFloats(1, 1);
  47552. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  47553. }
  47554. this.onActivateObservable.notifyObservers(camera);
  47555. // Clear
  47556. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  47557. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  47558. }
  47559. if (this._reusable) {
  47560. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  47561. }
  47562. };
  47563. Object.defineProperty(PostProcess.prototype, "isSupported", {
  47564. get: function () {
  47565. return this._effect.isSupported;
  47566. },
  47567. enumerable: true,
  47568. configurable: true
  47569. });
  47570. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  47571. get: function () {
  47572. if (this._shareOutputWithPostProcess) {
  47573. return this._shareOutputWithPostProcess.aspectRatio;
  47574. }
  47575. if (this._forcedOutputTexture) {
  47576. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  47577. }
  47578. return this.width / this.height;
  47579. },
  47580. enumerable: true,
  47581. configurable: true
  47582. });
  47583. PostProcess.prototype.apply = function () {
  47584. // Check
  47585. if (!this._effect || !this._effect.isReady())
  47586. return null;
  47587. // States
  47588. this._engine.enableEffect(this._effect);
  47589. this._engine.setState(false);
  47590. this._engine.setDepthBuffer(false);
  47591. this._engine.setDepthWrite(false);
  47592. // Alpha
  47593. this._engine.setAlphaMode(this.alphaMode);
  47594. if (this.alphaConstants) {
  47595. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  47596. }
  47597. // Texture
  47598. var source;
  47599. if (this._shareOutputWithPostProcess) {
  47600. source = this._shareOutputWithPostProcess.outputTexture;
  47601. }
  47602. else if (this._forcedOutputTexture) {
  47603. source = this._forcedOutputTexture;
  47604. }
  47605. else {
  47606. source = this.outputTexture;
  47607. }
  47608. this._effect._bindTexture("textureSampler", source);
  47609. // Parameters
  47610. this._effect.setVector2("scale", this._scaleRatio);
  47611. this.onApplyObservable.notifyObservers(this._effect);
  47612. return this._effect;
  47613. };
  47614. PostProcess.prototype._disposeTextures = function () {
  47615. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  47616. return;
  47617. }
  47618. if (this._textures.length > 0) {
  47619. for (var i = 0; i < this._textures.length; i++) {
  47620. this._engine._releaseTexture(this._textures.data[i]);
  47621. }
  47622. }
  47623. this._textures.dispose();
  47624. };
  47625. PostProcess.prototype.dispose = function (camera) {
  47626. camera = camera || this._camera;
  47627. this._disposeTextures();
  47628. if (this._scene) {
  47629. var index_1 = this._scene.postProcesses.indexOf(this);
  47630. if (index_1 !== -1) {
  47631. this._scene.postProcesses.splice(index_1, 1);
  47632. }
  47633. }
  47634. else {
  47635. var index_2 = this._engine.postProcesses.indexOf(this);
  47636. if (index_2 !== -1) {
  47637. this._engine.postProcesses.splice(index_2, 1);
  47638. }
  47639. }
  47640. if (!camera) {
  47641. return;
  47642. }
  47643. camera.detachPostProcess(this);
  47644. var index = camera._postProcesses.indexOf(this);
  47645. if (index === 0 && camera._postProcesses.length > 0) {
  47646. this._camera._postProcesses[0].markTextureDirty();
  47647. }
  47648. this.onActivateObservable.clear();
  47649. this.onAfterRenderObservable.clear();
  47650. this.onApplyObservable.clear();
  47651. this.onBeforeRenderObservable.clear();
  47652. this.onSizeChangedObservable.clear();
  47653. };
  47654. return PostProcess;
  47655. }());
  47656. BABYLON.PostProcess = PostProcess;
  47657. })(BABYLON || (BABYLON = {}));
  47658. //# sourceMappingURL=babylon.postProcess.js.map
  47659. var BABYLON;
  47660. (function (BABYLON) {
  47661. var PassPostProcess = (function (_super) {
  47662. __extends(PassPostProcess, _super);
  47663. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  47664. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47665. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  47666. }
  47667. return PassPostProcess;
  47668. }(BABYLON.PostProcess));
  47669. BABYLON.PassPostProcess = PassPostProcess;
  47670. })(BABYLON || (BABYLON = {}));
  47671. //# sourceMappingURL=babylon.passPostProcess.js.map
  47672. var BABYLON;
  47673. (function (BABYLON) {
  47674. var ShadowGenerator = (function () {
  47675. /**
  47676. * Creates a ShadowGenerator object.
  47677. * A ShadowGenerator is the required tool to use the shadows.
  47678. * Each light casting shadows needs to use its own ShadowGenerator.
  47679. * Required parameters :
  47680. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  47681. * - `light`: the light object generating the shadows.
  47682. * - `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.
  47683. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  47684. */
  47685. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  47686. // Members
  47687. this._bias = 0.00005;
  47688. this._blurBoxOffset = 1;
  47689. this._blurScale = 2;
  47690. this._blurKernel = 1;
  47691. this._useKernelBlur = false;
  47692. this._filter = ShadowGenerator.FILTER_NONE;
  47693. this._darkness = 0;
  47694. this._transparencyShadow = false;
  47695. /**
  47696. * Controls the extent to which the shadows fade out at the edge of the frustum
  47697. * Used only by directionals and spots
  47698. */
  47699. this.frustumEdgeFalloff = 0;
  47700. this.forceBackFacesOnly = false;
  47701. this._lightDirection = BABYLON.Vector3.Zero();
  47702. this._viewMatrix = BABYLON.Matrix.Zero();
  47703. this._projectionMatrix = BABYLON.Matrix.Zero();
  47704. this._transformMatrix = BABYLON.Matrix.Zero();
  47705. this._worldViewProjection = BABYLON.Matrix.Zero();
  47706. this._currentFaceIndex = 0;
  47707. this._currentFaceIndexCache = 0;
  47708. this._isCube = false;
  47709. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  47710. this._mapSize = mapSize;
  47711. this._light = light;
  47712. this._scene = light.getScene();
  47713. light._shadowGenerator = this;
  47714. // Texture type fallback from float to int if not supported.
  47715. var caps = this._scene.getEngine().getCaps();
  47716. if (!useFullFloatFirst) {
  47717. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  47718. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  47719. }
  47720. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  47721. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47722. }
  47723. else {
  47724. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47725. }
  47726. }
  47727. else {
  47728. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  47729. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47730. }
  47731. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  47732. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  47733. }
  47734. else {
  47735. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47736. }
  47737. }
  47738. this._initializeGenerator();
  47739. }
  47740. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  47741. // Static
  47742. get: function () {
  47743. return ShadowGenerator._FILTER_NONE;
  47744. },
  47745. enumerable: true,
  47746. configurable: true
  47747. });
  47748. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  47749. get: function () {
  47750. return ShadowGenerator._FILTER_POISSONSAMPLING;
  47751. },
  47752. enumerable: true,
  47753. configurable: true
  47754. });
  47755. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  47756. get: function () {
  47757. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  47758. },
  47759. enumerable: true,
  47760. configurable: true
  47761. });
  47762. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  47763. get: function () {
  47764. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  47765. },
  47766. enumerable: true,
  47767. configurable: true
  47768. });
  47769. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  47770. get: function () {
  47771. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  47772. },
  47773. enumerable: true,
  47774. configurable: true
  47775. });
  47776. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  47777. get: function () {
  47778. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  47779. },
  47780. enumerable: true,
  47781. configurable: true
  47782. });
  47783. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  47784. get: function () {
  47785. return this._bias;
  47786. },
  47787. set: function (bias) {
  47788. this._bias = bias;
  47789. },
  47790. enumerable: true,
  47791. configurable: true
  47792. });
  47793. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  47794. get: function () {
  47795. return this._blurBoxOffset;
  47796. },
  47797. set: function (value) {
  47798. if (this._blurBoxOffset === value) {
  47799. return;
  47800. }
  47801. this._blurBoxOffset = value;
  47802. this._disposeBlurPostProcesses();
  47803. },
  47804. enumerable: true,
  47805. configurable: true
  47806. });
  47807. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  47808. get: function () {
  47809. return this._blurScale;
  47810. },
  47811. set: function (value) {
  47812. if (this._blurScale === value) {
  47813. return;
  47814. }
  47815. this._blurScale = value;
  47816. this._disposeBlurPostProcesses();
  47817. },
  47818. enumerable: true,
  47819. configurable: true
  47820. });
  47821. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  47822. get: function () {
  47823. return this._blurKernel;
  47824. },
  47825. set: function (value) {
  47826. if (this._blurKernel === value) {
  47827. return;
  47828. }
  47829. this._blurKernel = value;
  47830. this._disposeBlurPostProcesses();
  47831. },
  47832. enumerable: true,
  47833. configurable: true
  47834. });
  47835. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  47836. get: function () {
  47837. return this._useKernelBlur;
  47838. },
  47839. set: function (value) {
  47840. if (this._useKernelBlur === value) {
  47841. return;
  47842. }
  47843. this._useKernelBlur = value;
  47844. this._disposeBlurPostProcesses();
  47845. },
  47846. enumerable: true,
  47847. configurable: true
  47848. });
  47849. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  47850. get: function () {
  47851. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  47852. },
  47853. set: function (value) {
  47854. this._depthScale = value;
  47855. },
  47856. enumerable: true,
  47857. configurable: true
  47858. });
  47859. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  47860. get: function () {
  47861. return this._filter;
  47862. },
  47863. set: function (value) {
  47864. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  47865. if (this._light.needCube()) {
  47866. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  47867. this.useExponentialShadowMap = true;
  47868. return;
  47869. }
  47870. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  47871. this.useCloseExponentialShadowMap = true;
  47872. return;
  47873. }
  47874. }
  47875. if (this._filter === value) {
  47876. return;
  47877. }
  47878. this._filter = value;
  47879. this._disposeBlurPostProcesses();
  47880. this._applyFilterValues();
  47881. this._light._markMeshesAsLightDirty();
  47882. },
  47883. enumerable: true,
  47884. configurable: true
  47885. });
  47886. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  47887. get: function () {
  47888. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  47889. },
  47890. set: function (value) {
  47891. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  47892. return;
  47893. }
  47894. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  47895. },
  47896. enumerable: true,
  47897. configurable: true
  47898. });
  47899. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  47900. get: function () {
  47901. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  47902. return this.useExponentialShadowMap;
  47903. },
  47904. set: function (value) {
  47905. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  47906. this.useExponentialShadowMap = value;
  47907. },
  47908. enumerable: true,
  47909. configurable: true
  47910. });
  47911. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  47912. get: function () {
  47913. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  47914. return this.useBlurExponentialShadowMap;
  47915. },
  47916. set: function (value) {
  47917. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  47918. this.useBlurExponentialShadowMap = value;
  47919. },
  47920. enumerable: true,
  47921. configurable: true
  47922. });
  47923. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  47924. get: function () {
  47925. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  47926. },
  47927. set: function (value) {
  47928. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  47929. return;
  47930. }
  47931. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47932. },
  47933. enumerable: true,
  47934. configurable: true
  47935. });
  47936. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  47937. get: function () {
  47938. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  47939. },
  47940. set: function (value) {
  47941. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  47942. return;
  47943. }
  47944. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47945. },
  47946. enumerable: true,
  47947. configurable: true
  47948. });
  47949. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  47950. get: function () {
  47951. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  47952. },
  47953. set: function (value) {
  47954. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  47955. return;
  47956. }
  47957. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47958. },
  47959. enumerable: true,
  47960. configurable: true
  47961. });
  47962. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  47963. get: function () {
  47964. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  47965. },
  47966. set: function (value) {
  47967. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  47968. return;
  47969. }
  47970. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47971. },
  47972. enumerable: true,
  47973. configurable: true
  47974. });
  47975. /**
  47976. * Returns the darkness value (float).
  47977. */
  47978. ShadowGenerator.prototype.getDarkness = function () {
  47979. return this._darkness;
  47980. };
  47981. /**
  47982. * Sets the ShadowGenerator darkness value (float <= 1.0).
  47983. * Returns the ShadowGenerator.
  47984. */
  47985. ShadowGenerator.prototype.setDarkness = function (darkness) {
  47986. if (darkness >= 1.0)
  47987. this._darkness = 1.0;
  47988. else if (darkness <= 0.0)
  47989. this._darkness = 0.0;
  47990. else
  47991. this._darkness = darkness;
  47992. return this;
  47993. };
  47994. /**
  47995. * Sets the ability to have transparent shadow (boolean).
  47996. * Returns the ShadowGenerator.
  47997. */
  47998. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  47999. this._transparencyShadow = hasShadow;
  48000. return this;
  48001. };
  48002. /**
  48003. * Returns a RenderTargetTexture object : the shadow map texture.
  48004. */
  48005. ShadowGenerator.prototype.getShadowMap = function () {
  48006. return this._shadowMap;
  48007. };
  48008. /**
  48009. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  48010. */
  48011. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  48012. if (this._shadowMap2) {
  48013. return this._shadowMap2;
  48014. }
  48015. return this._shadowMap;
  48016. };
  48017. /**
  48018. * Returns the associated light object.
  48019. */
  48020. ShadowGenerator.prototype.getLight = function () {
  48021. return this._light;
  48022. };
  48023. ShadowGenerator.prototype._initializeGenerator = function () {
  48024. this._light._markMeshesAsLightDirty();
  48025. this._initializeShadowMap();
  48026. };
  48027. ShadowGenerator.prototype._initializeShadowMap = function () {
  48028. var _this = this;
  48029. // Render target
  48030. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  48031. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48032. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48033. this._shadowMap.anisotropicFilteringLevel = 1;
  48034. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48035. this._shadowMap.renderParticles = false;
  48036. this._shadowMap.ignoreCameraViewport = true;
  48037. // Record Face Index before render.
  48038. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  48039. _this._currentFaceIndex = faceIndex;
  48040. });
  48041. // Custom render function.
  48042. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  48043. // Blur if required afer render.
  48044. this._shadowMap.onAfterUnbindObservable.add(function () {
  48045. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  48046. return;
  48047. }
  48048. if (!_this._blurPostProcesses) {
  48049. _this._initializeBlurRTTAndPostProcesses();
  48050. }
  48051. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture(), true);
  48052. });
  48053. // Clear according to the chosen filter.
  48054. this._shadowMap.onClearObservable.add(function (engine) {
  48055. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  48056. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  48057. }
  48058. else {
  48059. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  48060. }
  48061. });
  48062. };
  48063. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  48064. var _this = this;
  48065. var engine = this._scene.getEngine();
  48066. var targetSize = this._mapSize / this.blurScale;
  48067. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  48068. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  48069. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48070. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48071. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48072. }
  48073. if (this.useKernelBlur) {
  48074. 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);
  48075. this._kernelBlurXPostprocess.width = targetSize;
  48076. this._kernelBlurXPostprocess.height = targetSize;
  48077. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  48078. effect.setTexture("textureSampler", _this._shadowMap);
  48079. });
  48080. 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);
  48081. this._kernelBlurXPostprocess.autoClear = false;
  48082. this._kernelBlurYPostprocess.autoClear = false;
  48083. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  48084. this._kernelBlurXPostprocess.packedFloat = true;
  48085. this._kernelBlurYPostprocess.packedFloat = true;
  48086. }
  48087. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  48088. }
  48089. else {
  48090. 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);
  48091. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  48092. effect.setFloat2("screenSize", targetSize, targetSize);
  48093. effect.setTexture("textureSampler", _this._shadowMap);
  48094. });
  48095. this._boxBlurPostprocess.autoClear = false;
  48096. this._blurPostProcesses = [this._boxBlurPostprocess];
  48097. }
  48098. };
  48099. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  48100. var index;
  48101. var engine = this._scene.getEngine();
  48102. if (depthOnlySubMeshes.length) {
  48103. engine.setColorWrite(false);
  48104. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  48105. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  48106. }
  48107. engine.setColorWrite(true);
  48108. }
  48109. for (index = 0; index < opaqueSubMeshes.length; index++) {
  48110. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  48111. }
  48112. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  48113. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  48114. }
  48115. if (this._transparencyShadow) {
  48116. for (index = 0; index < transparentSubMeshes.length; index++) {
  48117. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  48118. }
  48119. }
  48120. };
  48121. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  48122. var _this = this;
  48123. var mesh = subMesh.getRenderingMesh();
  48124. var scene = this._scene;
  48125. var engine = scene.getEngine();
  48126. // Culling
  48127. engine.setState(subMesh.getMaterial().backFaceCulling);
  48128. // Managing instances
  48129. var batch = mesh._getInstancesRenderList(subMesh._id);
  48130. if (batch.mustReturn) {
  48131. return;
  48132. }
  48133. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  48134. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  48135. engine.enableEffect(this._effect);
  48136. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  48137. var material = subMesh.getMaterial();
  48138. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  48139. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  48140. this._effect.setVector3("lightPosition", this.getLight().position);
  48141. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  48142. // Alpha test
  48143. if (material && material.needAlphaTesting()) {
  48144. var alphaTexture = material.getAlphaTestTexture();
  48145. if (alphaTexture) {
  48146. this._effect.setTexture("diffuseSampler", alphaTexture);
  48147. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  48148. }
  48149. }
  48150. // Bones
  48151. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48152. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48153. }
  48154. if (this.forceBackFacesOnly) {
  48155. engine.setState(true, 0, false, true);
  48156. }
  48157. // Draw
  48158. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  48159. if (this.forceBackFacesOnly) {
  48160. engine.setState(true, 0, false, false);
  48161. }
  48162. }
  48163. else {
  48164. // Need to reset refresh rate of the shadowMap
  48165. this._shadowMap.resetRefreshCounter();
  48166. }
  48167. };
  48168. ShadowGenerator.prototype._applyFilterValues = function () {
  48169. if (this.filter === ShadowGenerator.FILTER_NONE) {
  48170. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  48171. }
  48172. else {
  48173. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48174. }
  48175. };
  48176. /**
  48177. * Force shader compilation including textures ready check
  48178. */
  48179. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  48180. var _this = this;
  48181. var scene = this._scene;
  48182. var engine = scene.getEngine();
  48183. var subMeshes = new Array();
  48184. var currentIndex = 0;
  48185. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  48186. var mesh = _a[_i];
  48187. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  48188. }
  48189. var checkReady = function () {
  48190. if (!_this._scene || !_this._scene.getEngine()) {
  48191. return;
  48192. }
  48193. var subMesh = subMeshes[currentIndex];
  48194. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  48195. currentIndex++;
  48196. if (currentIndex >= subMeshes.length) {
  48197. if (onCompiled) {
  48198. onCompiled(_this);
  48199. }
  48200. return;
  48201. }
  48202. }
  48203. setTimeout(checkReady, 16);
  48204. };
  48205. if (subMeshes.length > 0) {
  48206. checkReady();
  48207. }
  48208. };
  48209. /**
  48210. * Boolean : true when the ShadowGenerator is finally computed.
  48211. */
  48212. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  48213. var defines = [];
  48214. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  48215. defines.push("#define FLOAT");
  48216. }
  48217. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  48218. defines.push("#define ESM");
  48219. }
  48220. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48221. var mesh = subMesh.getMesh();
  48222. var material = subMesh.getMaterial();
  48223. // Alpha test
  48224. if (material && material.needAlphaTesting()) {
  48225. var alphaTexture = material.getAlphaTestTexture();
  48226. if (alphaTexture) {
  48227. defines.push("#define ALPHATEST");
  48228. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48229. attribs.push(BABYLON.VertexBuffer.UVKind);
  48230. defines.push("#define UV1");
  48231. }
  48232. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48233. if (alphaTexture.coordinatesIndex === 1) {
  48234. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48235. defines.push("#define UV2");
  48236. }
  48237. }
  48238. }
  48239. }
  48240. // Bones
  48241. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48242. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48243. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48244. if (mesh.numBoneInfluencers > 4) {
  48245. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48246. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48247. }
  48248. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48249. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48250. }
  48251. else {
  48252. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48253. }
  48254. // Instances
  48255. if (useInstances) {
  48256. defines.push("#define INSTANCES");
  48257. attribs.push("world0");
  48258. attribs.push("world1");
  48259. attribs.push("world2");
  48260. attribs.push("world3");
  48261. }
  48262. // Get correct effect
  48263. var join = defines.join("\n");
  48264. if (this._cachedDefines !== join) {
  48265. this._cachedDefines = join;
  48266. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  48267. }
  48268. return this._effect.isReady();
  48269. };
  48270. /**
  48271. * This creates the defines related to the standard BJS materials.
  48272. */
  48273. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  48274. var scene = this._scene;
  48275. var light = this._light;
  48276. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  48277. return;
  48278. }
  48279. defines["SHADOW" + lightIndex] = true;
  48280. if (this.usePoissonSampling) {
  48281. defines["SHADOWPCF" + lightIndex] = true;
  48282. }
  48283. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  48284. defines["SHADOWESM" + lightIndex] = true;
  48285. }
  48286. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  48287. defines["SHADOWCLOSEESM" + lightIndex] = true;
  48288. }
  48289. if (light.needCube()) {
  48290. defines["SHADOWCUBE" + lightIndex] = true;
  48291. }
  48292. };
  48293. /**
  48294. * This binds shadow lights related to the standard BJS materials.
  48295. * It implies the unifroms available on the materials are the standard BJS ones.
  48296. */
  48297. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  48298. var light = this._light;
  48299. var scene = this._scene;
  48300. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  48301. return;
  48302. }
  48303. if (!light.needCube()) {
  48304. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  48305. }
  48306. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  48307. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  48308. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  48309. };
  48310. // Methods
  48311. /**
  48312. * Returns a Matrix object : the updated transformation matrix.
  48313. */
  48314. ShadowGenerator.prototype.getTransformMatrix = function () {
  48315. var scene = this._scene;
  48316. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  48317. return this._transformMatrix;
  48318. }
  48319. this._currentRenderID = scene.getRenderId();
  48320. this._currentFaceIndexCache = this._currentFaceIndex;
  48321. var lightPosition = this._light.position;
  48322. if (this._light.computeTransformedInformation()) {
  48323. lightPosition = this._light.transformedPosition;
  48324. }
  48325. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  48326. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  48327. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  48328. }
  48329. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  48330. this._cachedPosition = lightPosition.clone();
  48331. this._cachedDirection = this._lightDirection.clone();
  48332. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  48333. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  48334. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  48335. }
  48336. return this._transformMatrix;
  48337. };
  48338. ShadowGenerator.prototype.recreateShadowMap = function () {
  48339. // Track render list.
  48340. var renderList = this._shadowMap.renderList;
  48341. // Clean up existing data.
  48342. this._disposeRTTandPostProcesses();
  48343. // Reinitializes.
  48344. this._initializeGenerator();
  48345. // Reaffect the filter to ensure a correct fallback if necessary.
  48346. this.filter = this.filter;
  48347. // Reaffect the filter.
  48348. this._applyFilterValues();
  48349. // Reaffect Render List.
  48350. this._shadowMap.renderList = renderList;
  48351. };
  48352. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  48353. if (this._shadowMap2) {
  48354. this._shadowMap2.dispose();
  48355. this._shadowMap2 = null;
  48356. }
  48357. if (this._downSamplePostprocess) {
  48358. this._downSamplePostprocess.dispose();
  48359. this._downSamplePostprocess = null;
  48360. }
  48361. if (this._boxBlurPostprocess) {
  48362. this._boxBlurPostprocess.dispose();
  48363. this._boxBlurPostprocess = null;
  48364. }
  48365. if (this._kernelBlurXPostprocess) {
  48366. this._kernelBlurXPostprocess.dispose();
  48367. this._kernelBlurXPostprocess = null;
  48368. }
  48369. if (this._kernelBlurYPostprocess) {
  48370. this._kernelBlurYPostprocess.dispose();
  48371. this._kernelBlurYPostprocess = null;
  48372. }
  48373. this._blurPostProcesses = null;
  48374. };
  48375. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  48376. if (this._shadowMap) {
  48377. this._shadowMap.dispose();
  48378. this._shadowMap = null;
  48379. }
  48380. this._disposeBlurPostProcesses();
  48381. };
  48382. /**
  48383. * Disposes the ShadowGenerator.
  48384. * Returns nothing.
  48385. */
  48386. ShadowGenerator.prototype.dispose = function () {
  48387. this._disposeRTTandPostProcesses();
  48388. this._light._shadowGenerator = null;
  48389. this._light._markMeshesAsLightDirty();
  48390. };
  48391. /**
  48392. * Serializes the ShadowGenerator and returns a serializationObject.
  48393. */
  48394. ShadowGenerator.prototype.serialize = function () {
  48395. var serializationObject = {};
  48396. var shadowMap = this.getShadowMap();
  48397. serializationObject.lightId = this._light.id;
  48398. serializationObject.mapSize = shadowMap.getRenderSize();
  48399. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  48400. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  48401. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  48402. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  48403. serializationObject.usePoissonSampling = this.usePoissonSampling;
  48404. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  48405. serializationObject.depthScale = this.depthScale;
  48406. serializationObject.darkness = this.getDarkness();
  48407. serializationObject.blurBoxOffset = this.blurBoxOffset;
  48408. serializationObject.blurKernel = this.blurKernel;
  48409. serializationObject.blurScale = this.blurScale;
  48410. serializationObject.useKernelBlur = this.useKernelBlur;
  48411. serializationObject.transparencyShadow = this._transparencyShadow;
  48412. serializationObject.renderList = [];
  48413. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  48414. var mesh = shadowMap.renderList[meshIndex];
  48415. serializationObject.renderList.push(mesh.id);
  48416. }
  48417. return serializationObject;
  48418. };
  48419. /**
  48420. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  48421. */
  48422. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  48423. //casting to point light, as light is missing the position attr and typescript complains.
  48424. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  48425. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  48426. var shadowMap = shadowGenerator.getShadowMap();
  48427. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  48428. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  48429. meshes.forEach(function (mesh) {
  48430. shadowMap.renderList.push(mesh);
  48431. });
  48432. }
  48433. if (parsedShadowGenerator.usePoissonSampling) {
  48434. shadowGenerator.usePoissonSampling = true;
  48435. }
  48436. else if (parsedShadowGenerator.useExponentialShadowMap) {
  48437. shadowGenerator.useExponentialShadowMap = true;
  48438. }
  48439. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  48440. shadowGenerator.useBlurExponentialShadowMap = true;
  48441. }
  48442. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  48443. shadowGenerator.useCloseExponentialShadowMap = true;
  48444. }
  48445. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  48446. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  48447. }
  48448. else if (parsedShadowGenerator.useVarianceShadowMap) {
  48449. shadowGenerator.useExponentialShadowMap = true;
  48450. }
  48451. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  48452. shadowGenerator.useBlurExponentialShadowMap = true;
  48453. }
  48454. if (parsedShadowGenerator.depthScale) {
  48455. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  48456. }
  48457. if (parsedShadowGenerator.blurScale) {
  48458. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  48459. }
  48460. if (parsedShadowGenerator.blurBoxOffset) {
  48461. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  48462. }
  48463. if (parsedShadowGenerator.useKernelBlur) {
  48464. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  48465. }
  48466. if (parsedShadowGenerator.blurKernel) {
  48467. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  48468. }
  48469. if (parsedShadowGenerator.bias !== undefined) {
  48470. shadowGenerator.bias = parsedShadowGenerator.bias;
  48471. }
  48472. if (parsedShadowGenerator.darkness) {
  48473. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  48474. }
  48475. if (parsedShadowGenerator.transparencyShadow) {
  48476. shadowGenerator.setTransparencyShadow(true);
  48477. }
  48478. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  48479. return shadowGenerator;
  48480. };
  48481. return ShadowGenerator;
  48482. }());
  48483. ShadowGenerator._FILTER_NONE = 0;
  48484. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  48485. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  48486. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  48487. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  48488. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  48489. BABYLON.ShadowGenerator = ShadowGenerator;
  48490. })(BABYLON || (BABYLON = {}));
  48491. //# sourceMappingURL=babylon.shadowGenerator.js.map
  48492. var BABYLON;
  48493. (function (BABYLON) {
  48494. var DefaultLoadingScreen = (function () {
  48495. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  48496. if (_loadingText === void 0) { _loadingText = ""; }
  48497. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  48498. var _this = this;
  48499. this._renderingCanvas = _renderingCanvas;
  48500. this._loadingText = _loadingText;
  48501. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  48502. // Resize
  48503. this._resizeLoadingUI = function () {
  48504. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  48505. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  48506. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  48507. _this._loadingDiv.style.left = canvasRect.left + "px";
  48508. _this._loadingDiv.style.top = canvasRect.top + "px";
  48509. _this._loadingDiv.style.width = canvasRect.width + "px";
  48510. _this._loadingDiv.style.height = canvasRect.height + "px";
  48511. };
  48512. }
  48513. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  48514. if (this._loadingDiv) {
  48515. // Do not add a loading screen if there is already one
  48516. return;
  48517. }
  48518. this._loadingDiv = document.createElement("div");
  48519. this._loadingDiv.id = "babylonjsLoadingDiv";
  48520. this._loadingDiv.style.opacity = "0";
  48521. this._loadingDiv.style.transition = "opacity 1.5s ease";
  48522. this._loadingDiv.style.pointerEvents = "none";
  48523. // Loading text
  48524. this._loadingTextDiv = document.createElement("div");
  48525. this._loadingTextDiv.style.position = "absolute";
  48526. this._loadingTextDiv.style.left = "0";
  48527. this._loadingTextDiv.style.top = "50%";
  48528. this._loadingTextDiv.style.marginTop = "80px";
  48529. this._loadingTextDiv.style.width = "100%";
  48530. this._loadingTextDiv.style.height = "20px";
  48531. this._loadingTextDiv.style.fontFamily = "Arial";
  48532. this._loadingTextDiv.style.fontSize = "14px";
  48533. this._loadingTextDiv.style.color = "white";
  48534. this._loadingTextDiv.style.textAlign = "center";
  48535. this._loadingTextDiv.innerHTML = "Loading";
  48536. this._loadingDiv.appendChild(this._loadingTextDiv);
  48537. //set the predefined text
  48538. this._loadingTextDiv.innerHTML = this._loadingText;
  48539. // Generating keyframes
  48540. var style = document.createElement('style');
  48541. style.type = 'text/css';
  48542. 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 }";
  48543. style.innerHTML = keyFrames;
  48544. document.getElementsByTagName('head')[0].appendChild(style);
  48545. // Loading img
  48546. var imgBack = new Image();
  48547. 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";
  48548. imgBack.style.position = "absolute";
  48549. imgBack.style.left = "50%";
  48550. imgBack.style.top = "50%";
  48551. imgBack.style.marginLeft = "-60px";
  48552. imgBack.style.marginTop = "-60px";
  48553. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  48554. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  48555. imgBack.style.transformOrigin = "50% 50%";
  48556. imgBack.style.webkitTransformOrigin = "50% 50%";
  48557. this._loadingDiv.appendChild(imgBack);
  48558. this._resizeLoadingUI();
  48559. window.addEventListener("resize", this._resizeLoadingUI);
  48560. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48561. document.body.appendChild(this._loadingDiv);
  48562. this._loadingDiv.style.opacity = "1";
  48563. };
  48564. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  48565. var _this = this;
  48566. if (!this._loadingDiv) {
  48567. return;
  48568. }
  48569. var onTransitionEnd = function () {
  48570. if (!_this._loadingDiv) {
  48571. return;
  48572. }
  48573. document.body.removeChild(_this._loadingDiv);
  48574. window.removeEventListener("resize", _this._resizeLoadingUI);
  48575. _this._loadingDiv = null;
  48576. };
  48577. this._loadingDiv.style.opacity = "0";
  48578. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  48579. };
  48580. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  48581. set: function (text) {
  48582. this._loadingText = text;
  48583. if (this._loadingTextDiv) {
  48584. this._loadingTextDiv.innerHTML = this._loadingText;
  48585. }
  48586. },
  48587. enumerable: true,
  48588. configurable: true
  48589. });
  48590. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  48591. get: function () {
  48592. return this._loadingDivBackgroundColor;
  48593. },
  48594. set: function (color) {
  48595. this._loadingDivBackgroundColor = color;
  48596. if (!this._loadingDiv) {
  48597. return;
  48598. }
  48599. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48600. },
  48601. enumerable: true,
  48602. configurable: true
  48603. });
  48604. return DefaultLoadingScreen;
  48605. }());
  48606. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  48607. })(BABYLON || (BABYLON = {}));
  48608. //# sourceMappingURL=babylon.loadingScreen.js.map
  48609. var BABYLON;
  48610. (function (BABYLON) {
  48611. var SceneLoader = (function () {
  48612. function SceneLoader() {
  48613. }
  48614. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  48615. get: function () {
  48616. return 0;
  48617. },
  48618. enumerable: true,
  48619. configurable: true
  48620. });
  48621. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  48622. get: function () {
  48623. return 1;
  48624. },
  48625. enumerable: true,
  48626. configurable: true
  48627. });
  48628. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  48629. get: function () {
  48630. return 2;
  48631. },
  48632. enumerable: true,
  48633. configurable: true
  48634. });
  48635. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  48636. get: function () {
  48637. return 3;
  48638. },
  48639. enumerable: true,
  48640. configurable: true
  48641. });
  48642. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  48643. get: function () {
  48644. return SceneLoader._ForceFullSceneLoadingForIncremental;
  48645. },
  48646. set: function (value) {
  48647. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  48648. },
  48649. enumerable: true,
  48650. configurable: true
  48651. });
  48652. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  48653. get: function () {
  48654. return SceneLoader._ShowLoadingScreen;
  48655. },
  48656. set: function (value) {
  48657. SceneLoader._ShowLoadingScreen = value;
  48658. },
  48659. enumerable: true,
  48660. configurable: true
  48661. });
  48662. Object.defineProperty(SceneLoader, "loggingLevel", {
  48663. get: function () {
  48664. return SceneLoader._loggingLevel;
  48665. },
  48666. set: function (value) {
  48667. SceneLoader._loggingLevel = value;
  48668. },
  48669. enumerable: true,
  48670. configurable: true
  48671. });
  48672. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  48673. get: function () {
  48674. return SceneLoader._CleanBoneMatrixWeights;
  48675. },
  48676. set: function (value) {
  48677. SceneLoader._CleanBoneMatrixWeights = value;
  48678. },
  48679. enumerable: true,
  48680. configurable: true
  48681. });
  48682. SceneLoader._getDefaultPlugin = function () {
  48683. return SceneLoader._registeredPlugins[".babylon"];
  48684. };
  48685. SceneLoader._getPluginForExtension = function (extension) {
  48686. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  48687. if (registeredPlugin) {
  48688. return registeredPlugin;
  48689. }
  48690. return SceneLoader._getDefaultPlugin();
  48691. };
  48692. SceneLoader._getPluginForDirectLoad = function (data) {
  48693. for (var extension in SceneLoader._registeredPlugins) {
  48694. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  48695. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  48696. return SceneLoader._registeredPlugins[extension];
  48697. }
  48698. }
  48699. return SceneLoader._getDefaultPlugin();
  48700. };
  48701. SceneLoader._getPluginForFilename = function (sceneFilename) {
  48702. if (sceneFilename.name) {
  48703. sceneFilename = sceneFilename.name;
  48704. }
  48705. var dotPosition = sceneFilename.lastIndexOf(".");
  48706. var queryStringPosition = sceneFilename.indexOf("?");
  48707. if (queryStringPosition === -1) {
  48708. queryStringPosition = sceneFilename.length;
  48709. }
  48710. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  48711. return SceneLoader._getPluginForExtension(extension);
  48712. };
  48713. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  48714. SceneLoader._getDirectLoad = function (sceneFilename) {
  48715. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  48716. return sceneFilename.substr(5);
  48717. }
  48718. return null;
  48719. };
  48720. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48721. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  48722. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  48723. var plugin = registeredPlugin.plugin;
  48724. var useArrayBuffer = registeredPlugin.isBinary;
  48725. var database;
  48726. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  48727. var dataCallback = function (data) {
  48728. if (scene.isDisposed) {
  48729. onError("Scene has been disposed");
  48730. return;
  48731. }
  48732. scene.database = database;
  48733. try {
  48734. onSuccess(plugin, data);
  48735. }
  48736. catch (e) {
  48737. onError(null, e);
  48738. }
  48739. };
  48740. var manifestChecked = function (success) {
  48741. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  48742. onError(request.status + " " + request.statusText);
  48743. });
  48744. };
  48745. if (directLoad) {
  48746. dataCallback(directLoad);
  48747. return;
  48748. }
  48749. if (rootUrl.indexOf("file:") === -1) {
  48750. if (scene.getEngine().enableOfflineSupport) {
  48751. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  48752. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  48753. }
  48754. else {
  48755. manifestChecked(true);
  48756. }
  48757. }
  48758. else {
  48759. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  48760. }
  48761. };
  48762. // Public functions
  48763. SceneLoader.GetPluginForExtension = function (extension) {
  48764. return SceneLoader._getPluginForExtension(extension).plugin;
  48765. };
  48766. SceneLoader.RegisterPlugin = function (plugin) {
  48767. if (typeof plugin.extensions === "string") {
  48768. var extension = plugin.extensions;
  48769. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48770. plugin: plugin,
  48771. isBinary: false
  48772. };
  48773. }
  48774. else {
  48775. var extensions = plugin.extensions;
  48776. Object.keys(extensions).forEach(function (extension) {
  48777. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48778. plugin: plugin,
  48779. isBinary: extensions[extension].isBinary
  48780. };
  48781. });
  48782. }
  48783. };
  48784. /**
  48785. * Import meshes into a scene
  48786. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  48787. * @param rootUrl a string that defines the root url for scene and resources
  48788. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48789. * @param scene the instance of BABYLON.Scene to append to
  48790. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  48791. * @param onProgress a callback with a progress event for each file being loaded
  48792. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48793. */
  48794. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48795. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48796. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48797. return;
  48798. }
  48799. var loadingToken = {};
  48800. scene._addPendingData(loadingToken);
  48801. var errorHandler = function (message, exception) {
  48802. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  48803. if (onError) {
  48804. onError(scene, errorMessage, exception);
  48805. }
  48806. else {
  48807. BABYLON.Tools.Error(errorMessage);
  48808. // should the exception be thrown?
  48809. }
  48810. scene._removePendingData(loadingToken);
  48811. };
  48812. var progressHandler = function (event) {
  48813. if (onProgress) {
  48814. onProgress(event);
  48815. }
  48816. };
  48817. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48818. if (plugin.importMesh) {
  48819. var syncedPlugin = plugin;
  48820. var meshes = [];
  48821. var particleSystems = [];
  48822. var skeletons = [];
  48823. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  48824. return;
  48825. }
  48826. if (onSuccess) {
  48827. // wrap onSuccess with try-catch to know if something went wrong.
  48828. try {
  48829. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48830. onSuccess(meshes, particleSystems, skeletons);
  48831. scene._removePendingData(loadingToken);
  48832. }
  48833. catch (e) {
  48834. var message = 'Error in onSuccess callback.';
  48835. errorHandler(message, e);
  48836. }
  48837. }
  48838. }
  48839. else {
  48840. var asyncedPlugin = plugin;
  48841. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  48842. if (onSuccess) {
  48843. try {
  48844. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48845. onSuccess(meshes, particleSystems, skeletons);
  48846. scene._removePendingData(loadingToken);
  48847. }
  48848. catch (e) {
  48849. var message = 'Error in onSuccess callback.';
  48850. errorHandler(message, e);
  48851. }
  48852. }
  48853. }, progressHandler, errorHandler);
  48854. }
  48855. }, progressHandler, errorHandler);
  48856. };
  48857. /**
  48858. * Load a scene
  48859. * @param rootUrl a string that defines the root url for scene and resources
  48860. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48861. * @param engine is the instance of BABYLON.Engine to use to create the scene
  48862. * @param onSuccess a callback with the scene when import succeeds
  48863. * @param onProgress a callback with a progress event for each file being loaded
  48864. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48865. */
  48866. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  48867. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  48868. };
  48869. /**
  48870. * Append a scene
  48871. * @param rootUrl a string that defines the root url for scene and resources
  48872. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48873. * @param scene is the instance of BABYLON.Scene to append to
  48874. * @param onSuccess a callback with the scene when import succeeds
  48875. * @param onProgress a callback with a progress event for each file being loaded
  48876. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48877. */
  48878. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48879. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48880. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48881. return;
  48882. }
  48883. if (SceneLoader.ShowLoadingScreen) {
  48884. scene.getEngine().displayLoadingUI();
  48885. }
  48886. var loadingToken = {};
  48887. scene._addPendingData(loadingToken);
  48888. var errorHandler = function (message, exception) {
  48889. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  48890. if (onError) {
  48891. onError(scene, errorMessage, exception);
  48892. }
  48893. else {
  48894. BABYLON.Tools.Error(errorMessage);
  48895. // should the exception be thrown?
  48896. }
  48897. scene._removePendingData(loadingToken);
  48898. scene.getEngine().hideLoadingUI();
  48899. };
  48900. var progressHandler = function (event) {
  48901. if (onProgress) {
  48902. onProgress(event);
  48903. }
  48904. };
  48905. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48906. if (plugin.load) {
  48907. var syncedPlugin = plugin;
  48908. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  48909. return;
  48910. }
  48911. if (onSuccess) {
  48912. try {
  48913. onSuccess(scene);
  48914. }
  48915. catch (e) {
  48916. errorHandler("Error in onSuccess callback", e);
  48917. }
  48918. }
  48919. scene.loadingPluginName = plugin.name;
  48920. scene._removePendingData(loadingToken);
  48921. }
  48922. else {
  48923. var asyncedPlugin = plugin;
  48924. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  48925. if (onSuccess) {
  48926. onSuccess(scene);
  48927. }
  48928. scene.loadingPluginName = plugin.name;
  48929. scene._removePendingData(loadingToken);
  48930. }, progressHandler, errorHandler);
  48931. }
  48932. if (SceneLoader.ShowLoadingScreen) {
  48933. scene.executeWhenReady(function () {
  48934. scene.getEngine().hideLoadingUI();
  48935. });
  48936. }
  48937. }, progressHandler, errorHandler);
  48938. };
  48939. return SceneLoader;
  48940. }());
  48941. // Flags
  48942. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  48943. SceneLoader._ShowLoadingScreen = true;
  48944. SceneLoader._CleanBoneMatrixWeights = false;
  48945. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  48946. // Members
  48947. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  48948. SceneLoader._registeredPlugins = {};
  48949. BABYLON.SceneLoader = SceneLoader;
  48950. ;
  48951. })(BABYLON || (BABYLON = {}));
  48952. //# sourceMappingURL=babylon.sceneLoader.js.map
  48953. var BABYLON;
  48954. (function (BABYLON) {
  48955. var Internals;
  48956. (function (Internals) {
  48957. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  48958. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  48959. var parsedMaterial = parsedData.materials[index];
  48960. if (parsedMaterial.id === id) {
  48961. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  48962. }
  48963. }
  48964. return null;
  48965. };
  48966. var isDescendantOf = function (mesh, names, hierarchyIds) {
  48967. for (var i in names) {
  48968. if (mesh.name === names[i]) {
  48969. hierarchyIds.push(mesh.id);
  48970. return true;
  48971. }
  48972. }
  48973. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  48974. hierarchyIds.push(mesh.id);
  48975. return true;
  48976. }
  48977. return false;
  48978. };
  48979. var logOperation = function (operation, producer) {
  48980. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  48981. };
  48982. BABYLON.SceneLoader.RegisterPlugin({
  48983. name: "babylon.js",
  48984. extensions: ".babylon",
  48985. canDirectLoad: function (data) {
  48986. if (data.indexOf("babylon") !== -1) {
  48987. return true;
  48988. }
  48989. return false;
  48990. },
  48991. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  48992. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48993. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48994. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48995. // and avoid problems with multiple concurrent .babylon loads.
  48996. var log = "importMesh has failed JSON parse";
  48997. try {
  48998. var parsedData = JSON.parse(data);
  48999. log = "";
  49000. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49001. if (!meshesNames) {
  49002. meshesNames = null;
  49003. }
  49004. else if (!Array.isArray(meshesNames)) {
  49005. meshesNames = [meshesNames];
  49006. }
  49007. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49008. var loadedSkeletonsIds = [];
  49009. var loadedMaterialsIds = [];
  49010. var hierarchyIds = [];
  49011. var index;
  49012. var cache;
  49013. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49014. var parsedMesh = parsedData.meshes[index];
  49015. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  49016. if (meshesNames !== null) {
  49017. // Remove found mesh name from list.
  49018. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  49019. }
  49020. //Geometry?
  49021. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  49022. //does the file contain geometries?
  49023. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  49024. //find the correct geometry and add it to the scene
  49025. var found = false;
  49026. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  49027. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  49028. return;
  49029. }
  49030. else {
  49031. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  49032. if (parsedGeometryData.id === parsedMesh.geometryId) {
  49033. switch (geometryType) {
  49034. case "boxes":
  49035. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  49036. break;
  49037. case "spheres":
  49038. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  49039. break;
  49040. case "cylinders":
  49041. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  49042. break;
  49043. case "toruses":
  49044. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  49045. break;
  49046. case "grounds":
  49047. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  49048. break;
  49049. case "planes":
  49050. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  49051. break;
  49052. case "torusKnots":
  49053. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  49054. break;
  49055. case "vertexData":
  49056. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  49057. break;
  49058. }
  49059. found = true;
  49060. }
  49061. });
  49062. }
  49063. });
  49064. if (found === false) {
  49065. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  49066. }
  49067. }
  49068. }
  49069. // Material ?
  49070. if (parsedMesh.materialId) {
  49071. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  49072. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49073. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  49074. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  49075. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  49076. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  49077. var subMatId = parsedMultiMaterial.materials[matIndex];
  49078. loadedMaterialsIds.push(subMatId);
  49079. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  49080. log += "\n\tMaterial " + mat.toString(fullDetails);
  49081. }
  49082. loadedMaterialsIds.push(parsedMultiMaterial.id);
  49083. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49084. materialFound = true;
  49085. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  49086. break;
  49087. }
  49088. }
  49089. }
  49090. if (materialFound === false) {
  49091. loadedMaterialsIds.push(parsedMesh.materialId);
  49092. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  49093. if (!mat) {
  49094. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  49095. }
  49096. else {
  49097. log += "\n\tMaterial " + mat.toString(fullDetails);
  49098. }
  49099. }
  49100. }
  49101. // Skeleton ?
  49102. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49103. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  49104. if (skeletonAlreadyLoaded === false) {
  49105. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  49106. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  49107. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  49108. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49109. skeletons.push(skeleton);
  49110. loadedSkeletonsIds.push(parsedSkeleton.id);
  49111. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  49112. }
  49113. }
  49114. }
  49115. }
  49116. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49117. meshes.push(mesh);
  49118. log += "\n\tMesh " + mesh.toString(fullDetails);
  49119. }
  49120. }
  49121. // Connecting parents
  49122. var currentMesh;
  49123. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49124. currentMesh = scene.meshes[index];
  49125. if (currentMesh._waitingParentId) {
  49126. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  49127. currentMesh._waitingParentId = undefined;
  49128. }
  49129. }
  49130. // freeze and compute world matrix application
  49131. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49132. currentMesh = scene.meshes[index];
  49133. if (currentMesh._waitingFreezeWorldMatrix) {
  49134. currentMesh.freezeWorldMatrix();
  49135. currentMesh._waitingFreezeWorldMatrix = undefined;
  49136. }
  49137. else {
  49138. currentMesh.computeWorldMatrix(true);
  49139. }
  49140. }
  49141. }
  49142. // Particles
  49143. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49144. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49145. var parsedParticleSystem = parsedData.particleSystems[index];
  49146. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  49147. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  49148. }
  49149. }
  49150. }
  49151. return true;
  49152. }
  49153. catch (err) {
  49154. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  49155. if (onError) {
  49156. onError(msg, err);
  49157. }
  49158. else {
  49159. BABYLON.Tools.Log(msg);
  49160. log = null;
  49161. throw err;
  49162. }
  49163. }
  49164. finally {
  49165. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49166. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49167. }
  49168. }
  49169. },
  49170. load: function (scene, data, rootUrl, onError) {
  49171. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49172. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49173. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49174. // and avoid problems with multiple concurrent .babylon loads.
  49175. var log = "importScene has failed JSON parse";
  49176. try {
  49177. var parsedData = JSON.parse(data);
  49178. log = "";
  49179. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49180. // Scene
  49181. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  49182. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  49183. }
  49184. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  49185. scene.autoClear = parsedData.autoClear;
  49186. }
  49187. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  49188. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  49189. }
  49190. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  49191. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  49192. }
  49193. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  49194. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  49195. }
  49196. // Fog
  49197. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  49198. scene.fogMode = parsedData.fogMode;
  49199. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  49200. scene.fogStart = parsedData.fogStart;
  49201. scene.fogEnd = parsedData.fogEnd;
  49202. scene.fogDensity = parsedData.fogDensity;
  49203. log += "\tFog mode for scene: ";
  49204. switch (scene.fogMode) {
  49205. // getters not compiling, so using hardcoded
  49206. case 1:
  49207. log += "exp\n";
  49208. break;
  49209. case 2:
  49210. log += "exp2\n";
  49211. break;
  49212. case 3:
  49213. log += "linear\n";
  49214. break;
  49215. }
  49216. }
  49217. //Physics
  49218. if (parsedData.physicsEnabled) {
  49219. var physicsPlugin;
  49220. if (parsedData.physicsEngine === "cannon") {
  49221. physicsPlugin = new BABYLON.CannonJSPlugin();
  49222. }
  49223. else if (parsedData.physicsEngine === "oimo") {
  49224. physicsPlugin = new BABYLON.OimoJSPlugin();
  49225. }
  49226. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  49227. //else - default engine, which is currently oimo
  49228. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  49229. scene.enablePhysics(physicsGravity, physicsPlugin);
  49230. }
  49231. // Metadata
  49232. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  49233. scene.metadata = parsedData.metadata;
  49234. }
  49235. //collisions, if defined. otherwise, default is true
  49236. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  49237. scene.collisionsEnabled = parsedData.collisionsEnabled;
  49238. }
  49239. scene.workerCollisions = !!parsedData.workerCollisions;
  49240. var index;
  49241. var cache;
  49242. // Lights
  49243. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  49244. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  49245. var parsedLight = parsedData.lights[index];
  49246. var light = BABYLON.Light.Parse(parsedLight, scene);
  49247. log += (index === 0 ? "\n\tLights:" : "");
  49248. log += "\n\t\t" + light.toString(fullDetails);
  49249. }
  49250. }
  49251. // Animations
  49252. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  49253. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  49254. var parsedAnimation = parsedData.animations[index];
  49255. var animation = BABYLON.Animation.Parse(parsedAnimation);
  49256. scene.animations.push(animation);
  49257. log += (index === 0 ? "\n\tAnimations:" : "");
  49258. log += "\n\t\t" + animation.toString(fullDetails);
  49259. }
  49260. }
  49261. if (parsedData.autoAnimate) {
  49262. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  49263. }
  49264. // Materials
  49265. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  49266. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49267. var parsedMaterial = parsedData.materials[index];
  49268. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49269. log += (index === 0 ? "\n\tMaterials:" : "");
  49270. log += "\n\t\t" + mat.toString(fullDetails);
  49271. }
  49272. }
  49273. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49274. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  49275. var parsedMultiMaterial = parsedData.multiMaterials[index];
  49276. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49277. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  49278. log += "\n\t\t" + mmat.toString(fullDetails);
  49279. }
  49280. }
  49281. // Morph targets
  49282. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  49283. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  49284. var managerData = _a[_i];
  49285. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  49286. }
  49287. }
  49288. // Skeletons
  49289. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49290. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  49291. var parsedSkeleton = parsedData.skeletons[index];
  49292. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49293. log += (index === 0 ? "\n\tSkeletons:" : "");
  49294. log += "\n\t\t" + skeleton.toString(fullDetails);
  49295. }
  49296. }
  49297. // Geometries
  49298. var geometries = parsedData.geometries;
  49299. if (geometries !== undefined && geometries !== null) {
  49300. // Boxes
  49301. var boxes = geometries.boxes;
  49302. if (boxes !== undefined && boxes !== null) {
  49303. for (index = 0, cache = boxes.length; index < cache; index++) {
  49304. var parsedBox = boxes[index];
  49305. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  49306. }
  49307. }
  49308. // Spheres
  49309. var spheres = geometries.spheres;
  49310. if (spheres !== undefined && spheres !== null) {
  49311. for (index = 0, cache = spheres.length; index < cache; index++) {
  49312. var parsedSphere = spheres[index];
  49313. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  49314. }
  49315. }
  49316. // Cylinders
  49317. var cylinders = geometries.cylinders;
  49318. if (cylinders !== undefined && cylinders !== null) {
  49319. for (index = 0, cache = cylinders.length; index < cache; index++) {
  49320. var parsedCylinder = cylinders[index];
  49321. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  49322. }
  49323. }
  49324. // Toruses
  49325. var toruses = geometries.toruses;
  49326. if (toruses !== undefined && toruses !== null) {
  49327. for (index = 0, cache = toruses.length; index < cache; index++) {
  49328. var parsedTorus = toruses[index];
  49329. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  49330. }
  49331. }
  49332. // Grounds
  49333. var grounds = geometries.grounds;
  49334. if (grounds !== undefined && grounds !== null) {
  49335. for (index = 0, cache = grounds.length; index < cache; index++) {
  49336. var parsedGround = grounds[index];
  49337. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  49338. }
  49339. }
  49340. // Planes
  49341. var planes = geometries.planes;
  49342. if (planes !== undefined && planes !== null) {
  49343. for (index = 0, cache = planes.length; index < cache; index++) {
  49344. var parsedPlane = planes[index];
  49345. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  49346. }
  49347. }
  49348. // TorusKnots
  49349. var torusKnots = geometries.torusKnots;
  49350. if (torusKnots !== undefined && torusKnots !== null) {
  49351. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  49352. var parsedTorusKnot = torusKnots[index];
  49353. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  49354. }
  49355. }
  49356. // VertexData
  49357. var vertexData = geometries.vertexData;
  49358. if (vertexData !== undefined && vertexData !== null) {
  49359. for (index = 0, cache = vertexData.length; index < cache; index++) {
  49360. var parsedVertexData = vertexData[index];
  49361. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  49362. }
  49363. }
  49364. }
  49365. // Meshes
  49366. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49367. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49368. var parsedMesh = parsedData.meshes[index];
  49369. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49370. log += (index === 0 ? "\n\tMeshes:" : "");
  49371. log += "\n\t\t" + mesh.toString(fullDetails);
  49372. }
  49373. }
  49374. // Cameras
  49375. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  49376. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  49377. var parsedCamera = parsedData.cameras[index];
  49378. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  49379. log += (index === 0 ? "\n\tCameras:" : "");
  49380. log += "\n\t\t" + camera.toString(fullDetails);
  49381. }
  49382. }
  49383. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  49384. scene.setActiveCameraByID(parsedData.activeCameraID);
  49385. }
  49386. // Browsing all the graph to connect the dots
  49387. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  49388. var camera = scene.cameras[index];
  49389. if (camera._waitingParentId) {
  49390. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  49391. camera._waitingParentId = undefined;
  49392. }
  49393. }
  49394. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49395. var light = scene.lights[index];
  49396. if (light._waitingParentId) {
  49397. light.parent = scene.getLastEntryByID(light._waitingParentId);
  49398. light._waitingParentId = undefined;
  49399. }
  49400. }
  49401. // Sounds
  49402. var loadedSounds = [];
  49403. var loadedSound;
  49404. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  49405. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  49406. var parsedSound = parsedData.sounds[index];
  49407. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49408. if (!parsedSound.url)
  49409. parsedSound.url = parsedSound.name;
  49410. if (!loadedSounds[parsedSound.url]) {
  49411. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  49412. loadedSounds[parsedSound.url] = loadedSound;
  49413. }
  49414. else {
  49415. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  49416. }
  49417. }
  49418. else {
  49419. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  49420. }
  49421. }
  49422. }
  49423. loadedSounds = [];
  49424. // Connect parents & children and parse actions
  49425. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49426. var mesh = scene.meshes[index];
  49427. if (mesh._waitingParentId) {
  49428. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  49429. mesh._waitingParentId = undefined;
  49430. }
  49431. if (mesh._waitingActions) {
  49432. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  49433. mesh._waitingActions = undefined;
  49434. }
  49435. }
  49436. // freeze world matrix application
  49437. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49438. var currentMesh = scene.meshes[index];
  49439. if (currentMesh._waitingFreezeWorldMatrix) {
  49440. currentMesh.freezeWorldMatrix();
  49441. currentMesh._waitingFreezeWorldMatrix = undefined;
  49442. }
  49443. else {
  49444. currentMesh.computeWorldMatrix(true);
  49445. }
  49446. }
  49447. // Particles Systems
  49448. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49449. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49450. var parsedParticleSystem = parsedData.particleSystems[index];
  49451. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  49452. }
  49453. }
  49454. // Lens flares
  49455. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  49456. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  49457. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  49458. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  49459. }
  49460. }
  49461. // Shadows
  49462. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  49463. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  49464. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  49465. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  49466. }
  49467. }
  49468. // Lights exclusions / inclusions
  49469. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49470. var light = scene.lights[index];
  49471. // Excluded check
  49472. if (light._excludedMeshesIds.length > 0) {
  49473. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  49474. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  49475. if (excludedMesh) {
  49476. light.excludedMeshes.push(excludedMesh);
  49477. }
  49478. }
  49479. light._excludedMeshesIds = [];
  49480. }
  49481. // Included check
  49482. if (light._includedOnlyMeshesIds.length > 0) {
  49483. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  49484. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  49485. if (includedOnlyMesh) {
  49486. light.includedOnlyMeshes.push(includedOnlyMesh);
  49487. }
  49488. }
  49489. light._includedOnlyMeshesIds = [];
  49490. }
  49491. }
  49492. // Actions (scene)
  49493. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  49494. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  49495. }
  49496. // Finish
  49497. return true;
  49498. }
  49499. catch (err) {
  49500. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  49501. if (onError) {
  49502. onError(msg, err);
  49503. }
  49504. else {
  49505. BABYLON.Tools.Log(msg);
  49506. log = null;
  49507. throw err;
  49508. }
  49509. }
  49510. finally {
  49511. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49512. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49513. }
  49514. }
  49515. }
  49516. });
  49517. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49518. })(BABYLON || (BABYLON = {}));
  49519. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  49520. var BABYLON;
  49521. (function (BABYLON) {
  49522. var FilesInput = (function () {
  49523. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  49524. this.onProcessFileCallback = function () { return true; };
  49525. this._engine = engine;
  49526. this._currentScene = scene;
  49527. this._sceneLoadedCallback = sceneLoadedCallback;
  49528. this._progressCallback = progressCallback;
  49529. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  49530. this._textureLoadingCallback = textureLoadingCallback;
  49531. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  49532. this._onReloadCallback = onReloadCallback;
  49533. this._errorCallback = errorCallback;
  49534. }
  49535. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  49536. var _this = this;
  49537. if (elementToMonitor) {
  49538. this._elementToMonitor = elementToMonitor;
  49539. this._dragEnterHandler = function (e) { _this.drag(e); };
  49540. this._dragOverHandler = function (e) { _this.drag(e); };
  49541. this._dropHandler = function (e) { _this.drop(e); };
  49542. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  49543. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  49544. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  49545. }
  49546. };
  49547. FilesInput.prototype.dispose = function () {
  49548. if (!this._elementToMonitor) {
  49549. return;
  49550. }
  49551. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  49552. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  49553. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  49554. };
  49555. FilesInput.prototype.renderFunction = function () {
  49556. if (this._additionalRenderLoopLogicCallback) {
  49557. this._additionalRenderLoopLogicCallback();
  49558. }
  49559. if (this._currentScene) {
  49560. if (this._textureLoadingCallback) {
  49561. var remaining = this._currentScene.getWaitingItemsCount();
  49562. if (remaining > 0) {
  49563. this._textureLoadingCallback(remaining);
  49564. }
  49565. }
  49566. this._currentScene.render();
  49567. }
  49568. };
  49569. FilesInput.prototype.drag = function (e) {
  49570. e.stopPropagation();
  49571. e.preventDefault();
  49572. };
  49573. FilesInput.prototype.drop = function (eventDrop) {
  49574. eventDrop.stopPropagation();
  49575. eventDrop.preventDefault();
  49576. this.loadFiles(eventDrop);
  49577. };
  49578. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  49579. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  49580. reader.readEntries(function (fileEntries) {
  49581. var remaining = fileEntries.length;
  49582. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  49583. var fileEntry = fileEntries_1[_i];
  49584. if (fileEntry.isFile) {
  49585. fileEntry.file(function (file) {
  49586. file.correctName = relativePath + file.name;
  49587. files.push(file);
  49588. remaining--;
  49589. if (remaining === 0) {
  49590. callback();
  49591. }
  49592. });
  49593. }
  49594. else {
  49595. remaining--;
  49596. if (remaining === 0) {
  49597. callback();
  49598. }
  49599. }
  49600. }
  49601. });
  49602. };
  49603. FilesInput.prototype._processFiles = function (files) {
  49604. var skippedFiles = 0;
  49605. for (var i = 0; i < files.length; i++) {
  49606. var name = files[i].correctName.toLowerCase();
  49607. var extension = name.split('.').pop();
  49608. if (!this.onProcessFileCallback(files[i], name, extension)) {
  49609. skippedFiles++;
  49610. continue;
  49611. }
  49612. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  49613. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  49614. this._sceneFileToLoad = files[i];
  49615. }
  49616. else {
  49617. FilesInput.FilesToLoad[name] = files[i];
  49618. }
  49619. }
  49620. if (this._onReloadCallback) {
  49621. this._onReloadCallback(this._sceneFileToLoad);
  49622. }
  49623. else if (skippedFiles < files.length) {
  49624. this.reload();
  49625. }
  49626. };
  49627. FilesInput.prototype.loadFiles = function (event) {
  49628. var _this = this;
  49629. if (this._startingProcessingFilesCallback)
  49630. this._startingProcessingFilesCallback();
  49631. // Handling data transfer via drag'n'drop
  49632. if (event && event.dataTransfer && event.dataTransfer.files) {
  49633. this._filesToLoad = event.dataTransfer.files;
  49634. }
  49635. // Handling files from input files
  49636. if (event && event.target && event.target.files) {
  49637. this._filesToLoad = event.target.files;
  49638. }
  49639. if (this._filesToLoad && this._filesToLoad.length > 0) {
  49640. var files_1 = [];
  49641. var folders = [];
  49642. var items = event.dataTransfer ? event.dataTransfer.items : null;
  49643. for (var i = 0; i < this._filesToLoad.length; i++) {
  49644. var fileToLoad = this._filesToLoad[i];
  49645. var name_1 = fileToLoad.name.toLowerCase();
  49646. var type = fileToLoad.type;
  49647. var entry = void 0;
  49648. fileToLoad.correctName = name_1;
  49649. if (items) {
  49650. var item = items[i];
  49651. if (item.getAsEntry) {
  49652. entry = item.getAsEntry();
  49653. }
  49654. else if (item.webkitGetAsEntry) {
  49655. entry = item.webkitGetAsEntry();
  49656. }
  49657. }
  49658. if (!entry) {
  49659. files_1.push(fileToLoad);
  49660. }
  49661. else {
  49662. if (entry.isDirectory) {
  49663. folders.push(entry);
  49664. }
  49665. else {
  49666. files_1.push(fileToLoad);
  49667. }
  49668. }
  49669. }
  49670. if (folders.length === 0) {
  49671. this._processFiles(files_1);
  49672. }
  49673. else {
  49674. var remaining = folders.length;
  49675. // Extract folder content
  49676. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  49677. var folder = folders_1[_i];
  49678. this._handleFolderDrop(folder, files_1, function () {
  49679. remaining--;
  49680. if (remaining === 0) {
  49681. _this._processFiles(files_1);
  49682. }
  49683. });
  49684. }
  49685. }
  49686. }
  49687. };
  49688. FilesInput.prototype.reload = function () {
  49689. var _this = this;
  49690. // If a ".babylon" file has been provided
  49691. if (this._sceneFileToLoad) {
  49692. if (this._currentScene) {
  49693. if (BABYLON.Tools.errorsCount > 0) {
  49694. BABYLON.Tools.ClearLogCache();
  49695. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  49696. }
  49697. this._engine.stopRenderLoop();
  49698. this._currentScene.dispose();
  49699. }
  49700. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  49701. _this._currentScene = newScene;
  49702. if (_this._sceneLoadedCallback) {
  49703. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  49704. }
  49705. // Wait for textures and shaders to be ready
  49706. _this._currentScene.executeWhenReady(function () {
  49707. _this._engine.runRenderLoop(function () {
  49708. _this.renderFunction();
  49709. });
  49710. });
  49711. }, function (progress) {
  49712. if (_this._progressCallback) {
  49713. _this._progressCallback(progress);
  49714. }
  49715. }, function (scene, message) {
  49716. _this._currentScene = scene;
  49717. if (_this._errorCallback) {
  49718. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  49719. }
  49720. });
  49721. }
  49722. else {
  49723. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  49724. }
  49725. };
  49726. return FilesInput;
  49727. }());
  49728. FilesInput.FilesToLoad = new Array();
  49729. BABYLON.FilesInput = FilesInput;
  49730. })(BABYLON || (BABYLON = {}));
  49731. //# sourceMappingURL=babylon.filesInput.js.map
  49732. var BABYLON;
  49733. (function (BABYLON) {
  49734. /**
  49735. * This class implement a typical dictionary using a string as key and the generic type T as value.
  49736. * The underlying implementation relies on an associative array to ensure the best performances.
  49737. * The value can be anything including 'null' but except 'undefined'
  49738. */
  49739. var StringDictionary = (function () {
  49740. function StringDictionary() {
  49741. this._count = 0;
  49742. this._data = {};
  49743. }
  49744. /**
  49745. * This will clear this dictionary and copy the content from the 'source' one.
  49746. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  49747. * @param source the dictionary to take the content from and copy to this dictionary
  49748. */
  49749. StringDictionary.prototype.copyFrom = function (source) {
  49750. var _this = this;
  49751. this.clear();
  49752. source.forEach(function (t, v) { return _this.add(t, v); });
  49753. };
  49754. /**
  49755. * Get a value based from its key
  49756. * @param key the given key to get the matching value from
  49757. * @return the value if found, otherwise undefined is returned
  49758. */
  49759. StringDictionary.prototype.get = function (key) {
  49760. var val = this._data[key];
  49761. if (val !== undefined) {
  49762. return val;
  49763. }
  49764. return undefined;
  49765. };
  49766. /**
  49767. * Get a value from its key or add it if it doesn't exist.
  49768. * This method will ensure you that a given key/data will be present in the dictionary.
  49769. * @param key the given key to get the matching value from
  49770. * @param factory the factory that will create the value if the key is not present in the dictionary.
  49771. * The factory will only be invoked if there's no data for the given key.
  49772. * @return the value corresponding to the key.
  49773. */
  49774. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  49775. var val = this.get(key);
  49776. if (val !== undefined) {
  49777. return val;
  49778. }
  49779. val = factory(key);
  49780. if (val) {
  49781. this.add(key, val);
  49782. }
  49783. return val;
  49784. };
  49785. /**
  49786. * Get a value from its key if present in the dictionary otherwise add it
  49787. * @param key the key to get the value from
  49788. * @param val if there's no such key/value pair in the dictionary add it with this value
  49789. * @return the value corresponding to the key
  49790. */
  49791. StringDictionary.prototype.getOrAdd = function (key, val) {
  49792. var curVal = this.get(key);
  49793. if (curVal !== undefined) {
  49794. return curVal;
  49795. }
  49796. this.add(key, val);
  49797. return val;
  49798. };
  49799. /**
  49800. * Check if there's a given key in the dictionary
  49801. * @param key the key to check for
  49802. * @return true if the key is present, false otherwise
  49803. */
  49804. StringDictionary.prototype.contains = function (key) {
  49805. return this._data[key] !== undefined;
  49806. };
  49807. /**
  49808. * Add a new key and its corresponding value
  49809. * @param key the key to add
  49810. * @param value the value corresponding to the key
  49811. * @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
  49812. */
  49813. StringDictionary.prototype.add = function (key, value) {
  49814. if (this._data[key] !== undefined) {
  49815. return false;
  49816. }
  49817. this._data[key] = value;
  49818. ++this._count;
  49819. return true;
  49820. };
  49821. StringDictionary.prototype.set = function (key, value) {
  49822. if (this._data[key] === undefined) {
  49823. return false;
  49824. }
  49825. this._data[key] = value;
  49826. return true;
  49827. };
  49828. /**
  49829. * Get the element of the given key and remove it from the dictionary
  49830. * @param key
  49831. */
  49832. StringDictionary.prototype.getAndRemove = function (key) {
  49833. var val = this.get(key);
  49834. if (val !== undefined) {
  49835. delete this._data[key];
  49836. --this._count;
  49837. return val;
  49838. }
  49839. return null;
  49840. };
  49841. /**
  49842. * Remove a key/value from the dictionary.
  49843. * @param key the key to remove
  49844. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  49845. */
  49846. StringDictionary.prototype.remove = function (key) {
  49847. if (this.contains(key)) {
  49848. delete this._data[key];
  49849. --this._count;
  49850. return true;
  49851. }
  49852. return false;
  49853. };
  49854. /**
  49855. * Clear the whole content of the dictionary
  49856. */
  49857. StringDictionary.prototype.clear = function () {
  49858. this._data = {};
  49859. this._count = 0;
  49860. };
  49861. Object.defineProperty(StringDictionary.prototype, "count", {
  49862. get: function () {
  49863. return this._count;
  49864. },
  49865. enumerable: true,
  49866. configurable: true
  49867. });
  49868. /**
  49869. * Execute a callback on each key/val of the dictionary.
  49870. * Note that you can remove any element in this dictionary in the callback implementation
  49871. * @param callback the callback to execute on a given key/value pair
  49872. */
  49873. StringDictionary.prototype.forEach = function (callback) {
  49874. for (var cur in this._data) {
  49875. var val = this._data[cur];
  49876. callback(cur, val);
  49877. }
  49878. };
  49879. /**
  49880. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  49881. * If the callback returns null or undefined the method will iterate to the next key/value pair
  49882. * Note that you can remove any element in this dictionary in the callback implementation
  49883. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  49884. */
  49885. StringDictionary.prototype.first = function (callback) {
  49886. for (var cur in this._data) {
  49887. var val = this._data[cur];
  49888. var res = callback(cur, val);
  49889. if (res) {
  49890. return res;
  49891. }
  49892. }
  49893. return null;
  49894. };
  49895. return StringDictionary;
  49896. }());
  49897. BABYLON.StringDictionary = StringDictionary;
  49898. })(BABYLON || (BABYLON = {}));
  49899. //# sourceMappingURL=babylon.stringDictionary.js.map
  49900. var BABYLON;
  49901. (function (BABYLON) {
  49902. var Tags = (function () {
  49903. function Tags() {
  49904. }
  49905. Tags.EnableFor = function (obj) {
  49906. obj._tags = obj._tags || {};
  49907. obj.hasTags = function () {
  49908. return Tags.HasTags(obj);
  49909. };
  49910. obj.addTags = function (tagsString) {
  49911. return Tags.AddTagsTo(obj, tagsString);
  49912. };
  49913. obj.removeTags = function (tagsString) {
  49914. return Tags.RemoveTagsFrom(obj, tagsString);
  49915. };
  49916. obj.matchesTagsQuery = function (tagsQuery) {
  49917. return Tags.MatchesQuery(obj, tagsQuery);
  49918. };
  49919. };
  49920. Tags.DisableFor = function (obj) {
  49921. delete obj._tags;
  49922. delete obj.hasTags;
  49923. delete obj.addTags;
  49924. delete obj.removeTags;
  49925. delete obj.matchesTagsQuery;
  49926. };
  49927. Tags.HasTags = function (obj) {
  49928. if (!obj._tags) {
  49929. return false;
  49930. }
  49931. return !BABYLON.Tools.IsEmpty(obj._tags);
  49932. };
  49933. Tags.GetTags = function (obj, asString) {
  49934. if (asString === void 0) { asString = true; }
  49935. if (!obj._tags) {
  49936. return null;
  49937. }
  49938. if (asString) {
  49939. var tagsArray = [];
  49940. for (var tag in obj._tags) {
  49941. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  49942. tagsArray.push(tag);
  49943. }
  49944. }
  49945. return tagsArray.join(" ");
  49946. }
  49947. else {
  49948. return obj._tags;
  49949. }
  49950. };
  49951. // the tags 'true' and 'false' are reserved and cannot be used as tags
  49952. // a tag cannot start with '||', '&&', and '!'
  49953. // it cannot contain whitespaces
  49954. Tags.AddTagsTo = function (obj, tagsString) {
  49955. if (!tagsString) {
  49956. return;
  49957. }
  49958. if (typeof tagsString !== "string") {
  49959. return;
  49960. }
  49961. var tags = tagsString.split(" ");
  49962. tags.forEach(function (tag, index, array) {
  49963. Tags._AddTagTo(obj, tag);
  49964. });
  49965. };
  49966. Tags._AddTagTo = function (obj, tag) {
  49967. tag = tag.trim();
  49968. if (tag === "" || tag === "true" || tag === "false") {
  49969. return;
  49970. }
  49971. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  49972. return;
  49973. }
  49974. Tags.EnableFor(obj);
  49975. obj._tags[tag] = true;
  49976. };
  49977. Tags.RemoveTagsFrom = function (obj, tagsString) {
  49978. if (!Tags.HasTags(obj)) {
  49979. return;
  49980. }
  49981. var tags = tagsString.split(" ");
  49982. for (var t in tags) {
  49983. Tags._RemoveTagFrom(obj, tags[t]);
  49984. }
  49985. };
  49986. Tags._RemoveTagFrom = function (obj, tag) {
  49987. delete obj._tags[tag];
  49988. };
  49989. Tags.MatchesQuery = function (obj, tagsQuery) {
  49990. if (tagsQuery === undefined) {
  49991. return true;
  49992. }
  49993. if (tagsQuery === "") {
  49994. return Tags.HasTags(obj);
  49995. }
  49996. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  49997. };
  49998. return Tags;
  49999. }());
  50000. BABYLON.Tags = Tags;
  50001. })(BABYLON || (BABYLON = {}));
  50002. //# sourceMappingURL=babylon.tags.js.map
  50003. var BABYLON;
  50004. (function (BABYLON) {
  50005. var Internals;
  50006. (function (Internals) {
  50007. var AndOrNotEvaluator = (function () {
  50008. function AndOrNotEvaluator() {
  50009. }
  50010. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  50011. if (!query.match(/\([^\(\)]*\)/g)) {
  50012. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  50013. }
  50014. else {
  50015. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  50016. // remove parenthesis
  50017. r = r.slice(1, r.length - 1);
  50018. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  50019. });
  50020. }
  50021. if (query === "true") {
  50022. return true;
  50023. }
  50024. if (query === "false") {
  50025. return false;
  50026. }
  50027. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  50028. };
  50029. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  50030. evaluateCallback = evaluateCallback || (function (r) {
  50031. return r === "true" ? true : false;
  50032. });
  50033. var result;
  50034. var or = parenthesisContent.split("||");
  50035. for (var i in or) {
  50036. if (or.hasOwnProperty(i)) {
  50037. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  50038. var and = ori.split("&&");
  50039. if (and.length > 1) {
  50040. for (var j = 0; j < and.length; ++j) {
  50041. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  50042. if (andj !== "true" && andj !== "false") {
  50043. if (andj[0] === "!") {
  50044. result = !evaluateCallback(andj.substring(1));
  50045. }
  50046. else {
  50047. result = evaluateCallback(andj);
  50048. }
  50049. }
  50050. else {
  50051. result = andj === "true" ? true : false;
  50052. }
  50053. if (!result) {
  50054. ori = "false";
  50055. break;
  50056. }
  50057. }
  50058. }
  50059. if (result || ori === "true") {
  50060. result = true;
  50061. break;
  50062. }
  50063. // result equals false (or undefined)
  50064. if (ori !== "true" && ori !== "false") {
  50065. if (ori[0] === "!") {
  50066. result = !evaluateCallback(ori.substring(1));
  50067. }
  50068. else {
  50069. result = evaluateCallback(ori);
  50070. }
  50071. }
  50072. else {
  50073. result = ori === "true" ? true : false;
  50074. }
  50075. }
  50076. }
  50077. // the whole parenthesis scope is replaced by 'true' or 'false'
  50078. return result ? "true" : "false";
  50079. };
  50080. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  50081. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  50082. // remove whitespaces
  50083. r = r.replace(/[\s]/g, function () { return ""; });
  50084. return r.length % 2 ? "!" : "";
  50085. });
  50086. booleanString = booleanString.trim();
  50087. if (booleanString === "!true") {
  50088. booleanString = "false";
  50089. }
  50090. else if (booleanString === "!false") {
  50091. booleanString = "true";
  50092. }
  50093. return booleanString;
  50094. };
  50095. return AndOrNotEvaluator;
  50096. }());
  50097. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  50098. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50099. })(BABYLON || (BABYLON = {}));
  50100. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  50101. var BABYLON;
  50102. (function (BABYLON) {
  50103. var Database = (function () {
  50104. function Database(urlToScene, callbackManifestChecked) {
  50105. // Handling various flavors of prefixed version of IndexedDB
  50106. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  50107. this.callbackManifestChecked = callbackManifestChecked;
  50108. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  50109. this.db = null;
  50110. this.enableSceneOffline = false;
  50111. this.enableTexturesOffline = false;
  50112. this.manifestVersionFound = 0;
  50113. this.mustUpdateRessources = false;
  50114. this.hasReachedQuota = false;
  50115. if (!Database.IDBStorageEnabled) {
  50116. this.callbackManifestChecked(true);
  50117. }
  50118. else {
  50119. this.checkManifestFile();
  50120. }
  50121. }
  50122. Database.prototype.checkManifestFile = function () {
  50123. var _this = this;
  50124. function noManifestFile() {
  50125. that.enableSceneOffline = false;
  50126. that.enableTexturesOffline = false;
  50127. that.callbackManifestChecked(false);
  50128. }
  50129. var that = this;
  50130. var timeStampUsed = false;
  50131. var manifestURL = this.currentSceneUrl + ".manifest";
  50132. var xhr = new XMLHttpRequest();
  50133. if (navigator.onLine) {
  50134. // Adding a timestamp to by-pass browsers' cache
  50135. timeStampUsed = true;
  50136. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  50137. }
  50138. xhr.open("GET", manifestURL, true);
  50139. xhr.addEventListener("load", function () {
  50140. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  50141. try {
  50142. var manifestFile = JSON.parse(xhr.response);
  50143. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  50144. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  50145. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  50146. _this.manifestVersionFound = manifestFile.version;
  50147. }
  50148. if (_this.callbackManifestChecked) {
  50149. _this.callbackManifestChecked(true);
  50150. }
  50151. }
  50152. catch (ex) {
  50153. noManifestFile();
  50154. }
  50155. }
  50156. else {
  50157. noManifestFile();
  50158. }
  50159. }, false);
  50160. xhr.addEventListener("error", function (event) {
  50161. if (timeStampUsed) {
  50162. timeStampUsed = false;
  50163. // Let's retry without the timeStamp
  50164. // It could fail when coupled with HTML5 Offline API
  50165. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  50166. xhr.open("GET", retryManifestURL, true);
  50167. xhr.send();
  50168. }
  50169. else {
  50170. noManifestFile();
  50171. }
  50172. }, false);
  50173. try {
  50174. xhr.send();
  50175. }
  50176. catch (ex) {
  50177. BABYLON.Tools.Error("Error on XHR send request.");
  50178. that.callbackManifestChecked(false);
  50179. }
  50180. };
  50181. Database.prototype.openAsync = function (successCallback, errorCallback) {
  50182. var _this = this;
  50183. function handleError() {
  50184. that.isSupported = false;
  50185. if (errorCallback)
  50186. errorCallback();
  50187. }
  50188. var that = this;
  50189. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  50190. // Your browser doesn't support IndexedDB
  50191. this.isSupported = false;
  50192. if (errorCallback)
  50193. errorCallback();
  50194. }
  50195. else {
  50196. // If the DB hasn't been opened or created yet
  50197. if (!this.db) {
  50198. this.hasReachedQuota = false;
  50199. this.isSupported = true;
  50200. var request = this.idbFactory.open("babylonjs", 1);
  50201. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  50202. request.onerror = function (event) {
  50203. handleError();
  50204. };
  50205. // executes when a version change transaction cannot complete due to other active transactions
  50206. request.onblocked = function (event) {
  50207. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  50208. handleError();
  50209. };
  50210. // DB has been opened successfully
  50211. request.onsuccess = function (event) {
  50212. _this.db = request.result;
  50213. successCallback();
  50214. };
  50215. // Initialization of the DB. Creating Scenes & Textures stores
  50216. request.onupgradeneeded = function (event) {
  50217. _this.db = (event.target).result;
  50218. try {
  50219. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  50220. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  50221. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  50222. }
  50223. catch (ex) {
  50224. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  50225. handleError();
  50226. }
  50227. };
  50228. }
  50229. else {
  50230. if (successCallback)
  50231. successCallback();
  50232. }
  50233. }
  50234. };
  50235. Database.prototype.loadImageFromDB = function (url, image) {
  50236. var _this = this;
  50237. var completeURL = Database.ReturnFullUrlLocation(url);
  50238. var saveAndLoadImage = function () {
  50239. if (!_this.hasReachedQuota && _this.db !== null) {
  50240. // the texture is not yet in the DB, let's try to save it
  50241. _this._saveImageIntoDBAsync(completeURL, image);
  50242. }
  50243. else {
  50244. image.src = url;
  50245. }
  50246. };
  50247. if (!this.mustUpdateRessources) {
  50248. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  50249. }
  50250. else {
  50251. saveAndLoadImage();
  50252. }
  50253. };
  50254. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  50255. if (this.isSupported && this.db !== null) {
  50256. var texture;
  50257. var transaction = this.db.transaction(["textures"]);
  50258. transaction.onabort = function (event) {
  50259. image.src = url;
  50260. };
  50261. transaction.oncomplete = function (event) {
  50262. var blobTextureURL;
  50263. if (texture) {
  50264. var URL = window.URL || window.webkitURL;
  50265. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  50266. image.onerror = function () {
  50267. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  50268. image.src = url;
  50269. };
  50270. image.src = blobTextureURL;
  50271. }
  50272. else {
  50273. notInDBCallback();
  50274. }
  50275. };
  50276. var getRequest = transaction.objectStore("textures").get(url);
  50277. getRequest.onsuccess = function (event) {
  50278. texture = (event.target).result;
  50279. };
  50280. getRequest.onerror = function (event) {
  50281. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  50282. image.src = url;
  50283. };
  50284. }
  50285. else {
  50286. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50287. image.src = url;
  50288. }
  50289. };
  50290. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  50291. var _this = this;
  50292. if (this.isSupported) {
  50293. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  50294. var generateBlobUrl = function () {
  50295. var blobTextureURL;
  50296. if (blob) {
  50297. var URL = window.URL || window.webkitURL;
  50298. try {
  50299. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  50300. }
  50301. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  50302. catch (ex) {
  50303. blobTextureURL = URL.createObjectURL(blob);
  50304. }
  50305. }
  50306. image.src = blobTextureURL;
  50307. };
  50308. if (Database.IsUASupportingBlobStorage) {
  50309. var xhr = new XMLHttpRequest(), blob;
  50310. xhr.open("GET", url, true);
  50311. xhr.responseType = "blob";
  50312. xhr.addEventListener("load", function () {
  50313. if (xhr.status === 200) {
  50314. // Blob as response (XHR2)
  50315. blob = xhr.response;
  50316. var transaction = _this.db.transaction(["textures"], "readwrite");
  50317. // the transaction could abort because of a QuotaExceededError error
  50318. transaction.onabort = function (event) {
  50319. try {
  50320. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  50321. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  50322. _this.hasReachedQuota = true;
  50323. }
  50324. }
  50325. catch (ex) { }
  50326. generateBlobUrl();
  50327. };
  50328. transaction.oncomplete = function (event) {
  50329. generateBlobUrl();
  50330. };
  50331. var newTexture = { textureUrl: url, data: blob };
  50332. try {
  50333. // Put the blob into the dabase
  50334. var addRequest = transaction.objectStore("textures").put(newTexture);
  50335. addRequest.onsuccess = function (event) {
  50336. };
  50337. addRequest.onerror = function (event) {
  50338. generateBlobUrl();
  50339. };
  50340. }
  50341. catch (ex) {
  50342. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  50343. if (ex.code === 25) {
  50344. Database.IsUASupportingBlobStorage = false;
  50345. }
  50346. image.src = url;
  50347. }
  50348. }
  50349. else {
  50350. image.src = url;
  50351. }
  50352. }, false);
  50353. xhr.addEventListener("error", function (event) {
  50354. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  50355. image.src = url;
  50356. }, false);
  50357. xhr.send();
  50358. }
  50359. else {
  50360. image.src = url;
  50361. }
  50362. }
  50363. else {
  50364. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50365. image.src = url;
  50366. }
  50367. };
  50368. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  50369. var _this = this;
  50370. var updateVersion = function (event) {
  50371. // the version is not yet in the DB or we need to update it
  50372. _this._saveVersionIntoDBAsync(url, versionLoaded);
  50373. };
  50374. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  50375. };
  50376. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  50377. var _this = this;
  50378. if (this.isSupported) {
  50379. var version;
  50380. try {
  50381. var transaction = this.db.transaction(["versions"]);
  50382. transaction.oncomplete = function (event) {
  50383. if (version) {
  50384. // If the version in the JSON file is > than the version in DB
  50385. if (_this.manifestVersionFound > version.data) {
  50386. _this.mustUpdateRessources = true;
  50387. updateInDBCallback();
  50388. }
  50389. else {
  50390. callback(version.data);
  50391. }
  50392. }
  50393. else {
  50394. _this.mustUpdateRessources = true;
  50395. updateInDBCallback();
  50396. }
  50397. };
  50398. transaction.onabort = function (event) {
  50399. callback(-1);
  50400. };
  50401. var getRequest = transaction.objectStore("versions").get(url);
  50402. getRequest.onsuccess = function (event) {
  50403. version = (event.target).result;
  50404. };
  50405. getRequest.onerror = function (event) {
  50406. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  50407. callback(-1);
  50408. };
  50409. }
  50410. catch (ex) {
  50411. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  50412. callback(-1);
  50413. }
  50414. }
  50415. else {
  50416. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50417. callback(-1);
  50418. }
  50419. };
  50420. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  50421. var _this = this;
  50422. if (this.isSupported && !this.hasReachedQuota) {
  50423. try {
  50424. // Open a transaction to the database
  50425. var transaction = this.db.transaction(["versions"], "readwrite");
  50426. // the transaction could abort because of a QuotaExceededError error
  50427. transaction.onabort = function (event) {
  50428. try {
  50429. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  50430. _this.hasReachedQuota = true;
  50431. }
  50432. }
  50433. catch (ex) { }
  50434. callback(-1);
  50435. };
  50436. transaction.oncomplete = function (event) {
  50437. callback(_this.manifestVersionFound);
  50438. };
  50439. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  50440. // Put the scene into the database
  50441. var addRequest = transaction.objectStore("versions").put(newVersion);
  50442. addRequest.onsuccess = function (event) {
  50443. };
  50444. addRequest.onerror = function (event) {
  50445. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  50446. };
  50447. }
  50448. catch (ex) {
  50449. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  50450. callback(-1);
  50451. }
  50452. }
  50453. else {
  50454. callback(-1);
  50455. }
  50456. };
  50457. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  50458. var _this = this;
  50459. var completeUrl = Database.ReturnFullUrlLocation(url);
  50460. var saveAndLoadFile = function (event) {
  50461. // the scene is not yet in the DB, let's try to save it
  50462. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  50463. };
  50464. this._checkVersionFromDB(completeUrl, function (version) {
  50465. if (version !== -1) {
  50466. if (!_this.mustUpdateRessources) {
  50467. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  50468. }
  50469. else {
  50470. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  50471. }
  50472. }
  50473. else {
  50474. errorCallback();
  50475. }
  50476. });
  50477. };
  50478. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  50479. if (this.isSupported) {
  50480. var targetStore;
  50481. if (url.indexOf(".babylon") !== -1) {
  50482. targetStore = "scenes";
  50483. }
  50484. else {
  50485. targetStore = "textures";
  50486. }
  50487. var file;
  50488. var transaction = this.db.transaction([targetStore]);
  50489. transaction.oncomplete = function (event) {
  50490. if (file) {
  50491. callback(file.data);
  50492. }
  50493. else {
  50494. notInDBCallback();
  50495. }
  50496. };
  50497. transaction.onabort = function (event) {
  50498. notInDBCallback();
  50499. };
  50500. var getRequest = transaction.objectStore(targetStore).get(url);
  50501. getRequest.onsuccess = function (event) {
  50502. file = (event.target).result;
  50503. };
  50504. getRequest.onerror = function (event) {
  50505. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  50506. notInDBCallback();
  50507. };
  50508. }
  50509. else {
  50510. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50511. callback();
  50512. }
  50513. };
  50514. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  50515. var _this = this;
  50516. if (this.isSupported) {
  50517. var targetStore;
  50518. if (url.indexOf(".babylon") !== -1) {
  50519. targetStore = "scenes";
  50520. }
  50521. else {
  50522. targetStore = "textures";
  50523. }
  50524. // Create XHR
  50525. var xhr = new XMLHttpRequest(), fileData;
  50526. xhr.open("GET", url, true);
  50527. if (useArrayBuffer) {
  50528. xhr.responseType = "arraybuffer";
  50529. }
  50530. xhr.onprogress = progressCallback;
  50531. xhr.addEventListener("load", function () {
  50532. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  50533. // Blob as response (XHR2)
  50534. //fileData = xhr.responseText;
  50535. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  50536. if (!_this.hasReachedQuota) {
  50537. // Open a transaction to the database
  50538. var transaction = _this.db.transaction([targetStore], "readwrite");
  50539. // the transaction could abort because of a QuotaExceededError error
  50540. transaction.onabort = function (event) {
  50541. try {
  50542. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  50543. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  50544. _this.hasReachedQuota = true;
  50545. }
  50546. }
  50547. catch (ex) { }
  50548. callback(fileData);
  50549. };
  50550. transaction.oncomplete = function (event) {
  50551. callback(fileData);
  50552. };
  50553. var newFile;
  50554. if (targetStore === "scenes") {
  50555. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  50556. }
  50557. else {
  50558. newFile = { textureUrl: url, data: fileData };
  50559. }
  50560. try {
  50561. // Put the scene into the database
  50562. var addRequest = transaction.objectStore(targetStore).put(newFile);
  50563. addRequest.onsuccess = function (event) {
  50564. };
  50565. addRequest.onerror = function (event) {
  50566. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  50567. };
  50568. }
  50569. catch (ex) {
  50570. callback(fileData);
  50571. }
  50572. }
  50573. else {
  50574. callback(fileData);
  50575. }
  50576. }
  50577. else {
  50578. callback();
  50579. }
  50580. }, false);
  50581. xhr.addEventListener("error", function (event) {
  50582. BABYLON.Tools.Error("error on XHR request.");
  50583. callback();
  50584. }, false);
  50585. xhr.send();
  50586. }
  50587. else {
  50588. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50589. callback();
  50590. }
  50591. };
  50592. return Database;
  50593. }());
  50594. Database.IsUASupportingBlobStorage = true;
  50595. Database.IDBStorageEnabled = true;
  50596. Database.parseURL = function (url) {
  50597. var a = document.createElement('a');
  50598. a.href = url;
  50599. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  50600. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  50601. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  50602. return absLocation;
  50603. };
  50604. Database.ReturnFullUrlLocation = function (url) {
  50605. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  50606. return (Database.parseURL(window.location.href) + url);
  50607. }
  50608. else {
  50609. return url;
  50610. }
  50611. };
  50612. BABYLON.Database = Database;
  50613. })(BABYLON || (BABYLON = {}));
  50614. //# sourceMappingURL=babylon.database.js.map
  50615. var BABYLON;
  50616. (function (BABYLON) {
  50617. var FresnelParameters = (function () {
  50618. function FresnelParameters() {
  50619. this._isEnabled = true;
  50620. this.leftColor = BABYLON.Color3.White();
  50621. this.rightColor = BABYLON.Color3.Black();
  50622. this.bias = 0;
  50623. this.power = 1;
  50624. }
  50625. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  50626. get: function () {
  50627. return this._isEnabled;
  50628. },
  50629. set: function (value) {
  50630. if (this._isEnabled === value) {
  50631. return;
  50632. }
  50633. this._isEnabled = value;
  50634. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  50635. },
  50636. enumerable: true,
  50637. configurable: true
  50638. });
  50639. FresnelParameters.prototype.clone = function () {
  50640. var newFresnelParameters = new FresnelParameters();
  50641. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  50642. return newFresnelParameters;
  50643. };
  50644. FresnelParameters.prototype.serialize = function () {
  50645. var serializationObject = {};
  50646. serializationObject.isEnabled = this.isEnabled;
  50647. serializationObject.leftColor = this.leftColor;
  50648. serializationObject.rightColor = this.rightColor;
  50649. serializationObject.bias = this.bias;
  50650. serializationObject.power = this.power;
  50651. return serializationObject;
  50652. };
  50653. FresnelParameters.Parse = function (parsedFresnelParameters) {
  50654. var fresnelParameters = new FresnelParameters();
  50655. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  50656. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  50657. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  50658. fresnelParameters.bias = parsedFresnelParameters.bias;
  50659. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  50660. return fresnelParameters;
  50661. };
  50662. return FresnelParameters;
  50663. }());
  50664. BABYLON.FresnelParameters = FresnelParameters;
  50665. })(BABYLON || (BABYLON = {}));
  50666. //# sourceMappingURL=babylon.fresnelParameters.js.map
  50667. var BABYLON;
  50668. (function (BABYLON) {
  50669. var MultiMaterial = (function (_super) {
  50670. __extends(MultiMaterial, _super);
  50671. function MultiMaterial(name, scene) {
  50672. var _this = _super.call(this, name, scene, true) || this;
  50673. scene.multiMaterials.push(_this);
  50674. _this.subMaterials = new Array();
  50675. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  50676. return _this;
  50677. }
  50678. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  50679. get: function () {
  50680. return this._subMaterials;
  50681. },
  50682. set: function (value) {
  50683. this._subMaterials = value;
  50684. this._hookArray(value);
  50685. },
  50686. enumerable: true,
  50687. configurable: true
  50688. });
  50689. MultiMaterial.prototype._hookArray = function (array) {
  50690. var _this = this;
  50691. var oldPush = array.push;
  50692. array.push = function () {
  50693. var items = [];
  50694. for (var _i = 0; _i < arguments.length; _i++) {
  50695. items[_i] = arguments[_i];
  50696. }
  50697. var result = oldPush.apply(array, items);
  50698. _this._markAllSubMeshesAsTexturesDirty();
  50699. return result;
  50700. };
  50701. var oldSplice = array.splice;
  50702. array.splice = function (index, deleteCount) {
  50703. var deleted = oldSplice.apply(array, [index, deleteCount]);
  50704. _this._markAllSubMeshesAsTexturesDirty();
  50705. return deleted;
  50706. };
  50707. };
  50708. // Properties
  50709. MultiMaterial.prototype.getSubMaterial = function (index) {
  50710. if (index < 0 || index >= this.subMaterials.length) {
  50711. return this.getScene().defaultMaterial;
  50712. }
  50713. return this.subMaterials[index];
  50714. };
  50715. MultiMaterial.prototype.getActiveTextures = function () {
  50716. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  50717. var _a;
  50718. };
  50719. // Methods
  50720. MultiMaterial.prototype.getClassName = function () {
  50721. return "MultiMaterial";
  50722. };
  50723. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  50724. for (var index = 0; index < this.subMaterials.length; index++) {
  50725. var subMaterial = this.subMaterials[index];
  50726. if (subMaterial) {
  50727. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  50728. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  50729. return false;
  50730. }
  50731. continue;
  50732. }
  50733. if (!this.subMaterials[index].isReady(mesh)) {
  50734. return false;
  50735. }
  50736. }
  50737. }
  50738. return true;
  50739. };
  50740. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  50741. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  50742. for (var index = 0; index < this.subMaterials.length; index++) {
  50743. var subMaterial = null;
  50744. if (cloneChildren) {
  50745. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  50746. }
  50747. else {
  50748. subMaterial = this.subMaterials[index];
  50749. }
  50750. newMultiMaterial.subMaterials.push(subMaterial);
  50751. }
  50752. return newMultiMaterial;
  50753. };
  50754. MultiMaterial.prototype.serialize = function () {
  50755. var serializationObject = {};
  50756. serializationObject.name = this.name;
  50757. serializationObject.id = this.id;
  50758. serializationObject.tags = BABYLON.Tags.GetTags(this);
  50759. serializationObject.materials = [];
  50760. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  50761. var subMat = this.subMaterials[matIndex];
  50762. if (subMat) {
  50763. serializationObject.materials.push(subMat.id);
  50764. }
  50765. else {
  50766. serializationObject.materials.push(null);
  50767. }
  50768. }
  50769. return serializationObject;
  50770. };
  50771. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  50772. var scene = this.getScene();
  50773. if (!scene) {
  50774. return;
  50775. }
  50776. var index = scene.multiMaterials.indexOf(this);
  50777. if (index >= 0) {
  50778. scene.multiMaterials.splice(index, 1);
  50779. }
  50780. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  50781. };
  50782. return MultiMaterial;
  50783. }(BABYLON.Material));
  50784. BABYLON.MultiMaterial = MultiMaterial;
  50785. })(BABYLON || (BABYLON = {}));
  50786. //# sourceMappingURL=babylon.multiMaterial.js.map
  50787. var BABYLON;
  50788. (function (BABYLON) {
  50789. var FreeCameraTouchInput = (function () {
  50790. function FreeCameraTouchInput() {
  50791. this._offsetX = null;
  50792. this._offsetY = null;
  50793. this._pointerCount = 0;
  50794. this._pointerPressed = [];
  50795. this.touchAngularSensibility = 200000.0;
  50796. this.touchMoveSensibility = 250.0;
  50797. }
  50798. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  50799. var _this = this;
  50800. var previousPosition;
  50801. if (this._pointerInput === undefined) {
  50802. this._onLostFocus = function (evt) {
  50803. _this._offsetX = null;
  50804. _this._offsetY = null;
  50805. };
  50806. this._pointerInput = function (p, s) {
  50807. var evt = p.event;
  50808. if (evt.pointerType === "mouse") {
  50809. return;
  50810. }
  50811. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50812. if (!noPreventDefault) {
  50813. evt.preventDefault();
  50814. }
  50815. _this._pointerPressed.push(evt.pointerId);
  50816. if (_this._pointerPressed.length !== 1) {
  50817. return;
  50818. }
  50819. previousPosition = {
  50820. x: evt.clientX,
  50821. y: evt.clientY
  50822. };
  50823. }
  50824. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  50825. if (!noPreventDefault) {
  50826. evt.preventDefault();
  50827. }
  50828. var index = _this._pointerPressed.indexOf(evt.pointerId);
  50829. if (index === -1) {
  50830. return;
  50831. }
  50832. _this._pointerPressed.splice(index, 1);
  50833. if (index != 0) {
  50834. return;
  50835. }
  50836. previousPosition = null;
  50837. _this._offsetX = null;
  50838. _this._offsetY = null;
  50839. }
  50840. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  50841. if (!noPreventDefault) {
  50842. evt.preventDefault();
  50843. }
  50844. if (!previousPosition) {
  50845. return;
  50846. }
  50847. var index = _this._pointerPressed.indexOf(evt.pointerId);
  50848. if (index != 0) {
  50849. return;
  50850. }
  50851. _this._offsetX = evt.clientX - previousPosition.x;
  50852. _this._offsetY = -(evt.clientY - previousPosition.y);
  50853. }
  50854. };
  50855. }
  50856. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  50857. element.addEventListener("blur", this._onLostFocus);
  50858. };
  50859. FreeCameraTouchInput.prototype.detachControl = function (element) {
  50860. if (this._pointerInput && element) {
  50861. this.camera.getScene().onPointerObservable.remove(this._observer);
  50862. this._observer = null;
  50863. element.removeEventListener("blur", this._onLostFocus);
  50864. this._onLostFocus = null;
  50865. this._pointerPressed = [];
  50866. this._offsetX = null;
  50867. this._offsetY = null;
  50868. this._pointerCount = 0;
  50869. }
  50870. };
  50871. FreeCameraTouchInput.prototype.checkInputs = function () {
  50872. if (this._offsetX) {
  50873. var camera = this.camera;
  50874. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  50875. if (this._pointerPressed.length > 1) {
  50876. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  50877. }
  50878. else {
  50879. var speed = camera._computeLocalCameraSpeed();
  50880. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  50881. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  50882. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  50883. }
  50884. }
  50885. };
  50886. FreeCameraTouchInput.prototype.getClassName = function () {
  50887. return "FreeCameraTouchInput";
  50888. };
  50889. FreeCameraTouchInput.prototype.getSimpleName = function () {
  50890. return "touch";
  50891. };
  50892. return FreeCameraTouchInput;
  50893. }());
  50894. __decorate([
  50895. BABYLON.serialize()
  50896. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  50897. __decorate([
  50898. BABYLON.serialize()
  50899. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  50900. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  50901. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  50902. })(BABYLON || (BABYLON = {}));
  50903. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  50904. /// <reference path="babylon.freeCamera.ts" />
  50905. var BABYLON;
  50906. (function (BABYLON) {
  50907. // We're mainly based on the logic defined into the FreeCamera code
  50908. var TouchCamera = (function (_super) {
  50909. __extends(TouchCamera, _super);
  50910. //-- end properties for backward compatibility for inputs
  50911. function TouchCamera(name, position, scene) {
  50912. var _this = _super.call(this, name, position, scene) || this;
  50913. _this.inputs.addTouch();
  50914. _this._setupInputs();
  50915. return _this;
  50916. }
  50917. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  50918. //-- Begin properties for backward compatibility for inputs
  50919. get: function () {
  50920. var touch = this.inputs.attached["touch"];
  50921. if (touch)
  50922. return touch.touchAngularSensibility;
  50923. },
  50924. set: function (value) {
  50925. var touch = this.inputs.attached["touch"];
  50926. if (touch)
  50927. touch.touchAngularSensibility = value;
  50928. },
  50929. enumerable: true,
  50930. configurable: true
  50931. });
  50932. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  50933. get: function () {
  50934. var touch = this.inputs.attached["touch"];
  50935. if (touch)
  50936. return touch.touchMoveSensibility;
  50937. },
  50938. set: function (value) {
  50939. var touch = this.inputs.attached["touch"];
  50940. if (touch)
  50941. touch.touchMoveSensibility = value;
  50942. },
  50943. enumerable: true,
  50944. configurable: true
  50945. });
  50946. TouchCamera.prototype.getClassName = function () {
  50947. return "TouchCamera";
  50948. };
  50949. TouchCamera.prototype._setupInputs = function () {
  50950. var mouse = this.inputs.attached["mouse"];
  50951. if (mouse) {
  50952. mouse.touchEnabled = false;
  50953. }
  50954. };
  50955. return TouchCamera;
  50956. }(BABYLON.FreeCamera));
  50957. BABYLON.TouchCamera = TouchCamera;
  50958. })(BABYLON || (BABYLON = {}));
  50959. //# sourceMappingURL=babylon.touchCamera.js.map
  50960. var BABYLON;
  50961. (function (BABYLON) {
  50962. var ProceduralTexture = (function (_super) {
  50963. __extends(ProceduralTexture, _super);
  50964. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  50965. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50966. if (isCube === void 0) { isCube = false; }
  50967. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  50968. _this.isCube = isCube;
  50969. _this.isEnabled = true;
  50970. _this._currentRefreshId = -1;
  50971. _this._refreshRate = 1;
  50972. _this._vertexBuffers = {};
  50973. _this._uniforms = new Array();
  50974. _this._samplers = new Array();
  50975. _this._textures = new Array();
  50976. _this._floats = new Array();
  50977. _this._floatsArrays = {};
  50978. _this._colors3 = new Array();
  50979. _this._colors4 = new Array();
  50980. _this._vectors2 = new Array();
  50981. _this._vectors3 = new Array();
  50982. _this._matrices = new Array();
  50983. _this._fallbackTextureUsed = false;
  50984. scene._proceduralTextures.push(_this);
  50985. _this.name = name;
  50986. _this.isRenderTarget = true;
  50987. _this._size = size;
  50988. _this._generateMipMaps = generateMipMaps;
  50989. _this.setFragment(fragment);
  50990. _this._fallbackTexture = fallbackTexture;
  50991. var engine = scene.getEngine();
  50992. if (isCube) {
  50993. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  50994. _this.setFloat("face", 0);
  50995. }
  50996. else {
  50997. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  50998. }
  50999. // VBO
  51000. var vertices = [];
  51001. vertices.push(1, 1);
  51002. vertices.push(-1, 1);
  51003. vertices.push(-1, -1);
  51004. vertices.push(1, -1);
  51005. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  51006. _this._createIndexBuffer();
  51007. return _this;
  51008. }
  51009. ProceduralTexture.prototype._createIndexBuffer = function () {
  51010. var engine = this.getScene().getEngine();
  51011. // Indices
  51012. var indices = [];
  51013. indices.push(0);
  51014. indices.push(1);
  51015. indices.push(2);
  51016. indices.push(0);
  51017. indices.push(2);
  51018. indices.push(3);
  51019. this._indexBuffer = engine.createIndexBuffer(indices);
  51020. };
  51021. ProceduralTexture.prototype._rebuild = function () {
  51022. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  51023. this._createIndexBuffer();
  51024. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  51025. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  51026. }
  51027. };
  51028. ProceduralTexture.prototype.reset = function () {
  51029. if (this._effect === undefined) {
  51030. return;
  51031. }
  51032. var engine = this.getScene().getEngine();
  51033. engine._releaseEffect(this._effect);
  51034. };
  51035. ProceduralTexture.prototype.isReady = function () {
  51036. var _this = this;
  51037. var engine = this.getScene().getEngine();
  51038. var shaders;
  51039. if (!this._fragment) {
  51040. return false;
  51041. }
  51042. if (this._fallbackTextureUsed) {
  51043. return true;
  51044. }
  51045. if (this._fragment.fragmentElement !== undefined) {
  51046. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  51047. }
  51048. else {
  51049. shaders = { vertex: "procedural", fragment: this._fragment };
  51050. }
  51051. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  51052. _this.releaseInternalTexture();
  51053. if (_this._fallbackTexture) {
  51054. _this._texture = _this._fallbackTexture._texture;
  51055. _this._texture.incrementReferences();
  51056. }
  51057. _this._fallbackTextureUsed = true;
  51058. });
  51059. return this._effect.isReady();
  51060. };
  51061. ProceduralTexture.prototype.resetRefreshCounter = function () {
  51062. this._currentRefreshId = -1;
  51063. };
  51064. ProceduralTexture.prototype.setFragment = function (fragment) {
  51065. this._fragment = fragment;
  51066. };
  51067. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  51068. get: function () {
  51069. return this._refreshRate;
  51070. },
  51071. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  51072. set: function (value) {
  51073. this._refreshRate = value;
  51074. this.resetRefreshCounter();
  51075. },
  51076. enumerable: true,
  51077. configurable: true
  51078. });
  51079. ProceduralTexture.prototype._shouldRender = function () {
  51080. if (!this.isEnabled || !this.isReady() || !this._texture) {
  51081. return false;
  51082. }
  51083. if (this._fallbackTextureUsed) {
  51084. return false;
  51085. }
  51086. if (this._currentRefreshId === -1) {
  51087. this._currentRefreshId = 1;
  51088. return true;
  51089. }
  51090. if (this.refreshRate === this._currentRefreshId) {
  51091. this._currentRefreshId = 1;
  51092. return true;
  51093. }
  51094. this._currentRefreshId++;
  51095. return false;
  51096. };
  51097. ProceduralTexture.prototype.getRenderSize = function () {
  51098. return this._size;
  51099. };
  51100. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  51101. if (this._fallbackTextureUsed) {
  51102. return;
  51103. }
  51104. this.releaseInternalTexture();
  51105. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  51106. };
  51107. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  51108. if (this._uniforms.indexOf(uniformName) === -1) {
  51109. this._uniforms.push(uniformName);
  51110. }
  51111. };
  51112. ProceduralTexture.prototype.setTexture = function (name, texture) {
  51113. if (this._samplers.indexOf(name) === -1) {
  51114. this._samplers.push(name);
  51115. }
  51116. this._textures[name] = texture;
  51117. return this;
  51118. };
  51119. ProceduralTexture.prototype.setFloat = function (name, value) {
  51120. this._checkUniform(name);
  51121. this._floats[name] = value;
  51122. return this;
  51123. };
  51124. ProceduralTexture.prototype.setFloats = function (name, value) {
  51125. this._checkUniform(name);
  51126. this._floatsArrays[name] = value;
  51127. return this;
  51128. };
  51129. ProceduralTexture.prototype.setColor3 = function (name, value) {
  51130. this._checkUniform(name);
  51131. this._colors3[name] = value;
  51132. return this;
  51133. };
  51134. ProceduralTexture.prototype.setColor4 = function (name, value) {
  51135. this._checkUniform(name);
  51136. this._colors4[name] = value;
  51137. return this;
  51138. };
  51139. ProceduralTexture.prototype.setVector2 = function (name, value) {
  51140. this._checkUniform(name);
  51141. this._vectors2[name] = value;
  51142. return this;
  51143. };
  51144. ProceduralTexture.prototype.setVector3 = function (name, value) {
  51145. this._checkUniform(name);
  51146. this._vectors3[name] = value;
  51147. return this;
  51148. };
  51149. ProceduralTexture.prototype.setMatrix = function (name, value) {
  51150. this._checkUniform(name);
  51151. this._matrices[name] = value;
  51152. return this;
  51153. };
  51154. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  51155. var scene = this.getScene();
  51156. var engine = scene.getEngine();
  51157. // Render
  51158. engine.enableEffect(this._effect);
  51159. engine.setState(false);
  51160. // Texture
  51161. for (var name in this._textures) {
  51162. this._effect.setTexture(name, this._textures[name]);
  51163. }
  51164. // Float
  51165. for (name in this._floats) {
  51166. this._effect.setFloat(name, this._floats[name]);
  51167. }
  51168. // Floats
  51169. for (name in this._floatsArrays) {
  51170. this._effect.setArray(name, this._floatsArrays[name]);
  51171. }
  51172. // Color3
  51173. for (name in this._colors3) {
  51174. this._effect.setColor3(name, this._colors3[name]);
  51175. }
  51176. // Color4
  51177. for (name in this._colors4) {
  51178. var color = this._colors4[name];
  51179. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  51180. }
  51181. // Vector2
  51182. for (name in this._vectors2) {
  51183. this._effect.setVector2(name, this._vectors2[name]);
  51184. }
  51185. // Vector3
  51186. for (name in this._vectors3) {
  51187. this._effect.setVector3(name, this._vectors3[name]);
  51188. }
  51189. // Matrix
  51190. for (name in this._matrices) {
  51191. this._effect.setMatrix(name, this._matrices[name]);
  51192. }
  51193. if (this.isCube) {
  51194. for (var face = 0; face < 6; face++) {
  51195. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  51196. // VBOs
  51197. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  51198. this._effect.setFloat("face", face);
  51199. // Clear
  51200. engine.clear(scene.clearColor, true, true, true);
  51201. // Draw order
  51202. engine.draw(true, 0, 6);
  51203. // Mipmaps
  51204. if (face === 5) {
  51205. engine.generateMipMapsForCubemap(this._texture);
  51206. }
  51207. }
  51208. }
  51209. else {
  51210. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  51211. // VBOs
  51212. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  51213. // Clear
  51214. engine.clear(scene.clearColor, true, true, true);
  51215. // Draw order
  51216. engine.draw(true, 0, 6);
  51217. }
  51218. // Unbind
  51219. engine.unBindFramebuffer(this._texture, this.isCube);
  51220. if (this.onGenerated) {
  51221. this.onGenerated();
  51222. }
  51223. };
  51224. ProceduralTexture.prototype.clone = function () {
  51225. var textureSize = this.getSize();
  51226. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  51227. // Base texture
  51228. newTexture.hasAlpha = this.hasAlpha;
  51229. newTexture.level = this.level;
  51230. // RenderTarget Texture
  51231. newTexture.coordinatesMode = this.coordinatesMode;
  51232. return newTexture;
  51233. };
  51234. ProceduralTexture.prototype.dispose = function () {
  51235. var index = this.getScene()._proceduralTextures.indexOf(this);
  51236. if (index >= 0) {
  51237. this.getScene()._proceduralTextures.splice(index, 1);
  51238. }
  51239. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  51240. if (vertexBuffer) {
  51241. vertexBuffer.dispose();
  51242. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  51243. }
  51244. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  51245. this._indexBuffer = null;
  51246. }
  51247. _super.prototype.dispose.call(this);
  51248. };
  51249. return ProceduralTexture;
  51250. }(BABYLON.Texture));
  51251. BABYLON.ProceduralTexture = ProceduralTexture;
  51252. })(BABYLON || (BABYLON = {}));
  51253. //# sourceMappingURL=babylon.proceduralTexture.js.map
  51254. /// <reference path="babylon.proceduralTexture.ts" />
  51255. var BABYLON;
  51256. (function (BABYLON) {
  51257. var CustomProceduralTexture = (function (_super) {
  51258. __extends(CustomProceduralTexture, _super);
  51259. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  51260. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  51261. _this._animate = true;
  51262. _this._time = 0;
  51263. _this._texturePath = texturePath;
  51264. //Try to load json
  51265. _this.loadJson(texturePath);
  51266. _this.refreshRate = 1;
  51267. return _this;
  51268. }
  51269. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  51270. var _this = this;
  51271. var that = this;
  51272. function noConfigFile() {
  51273. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  51274. try {
  51275. that.setFragment(that._texturePath);
  51276. }
  51277. catch (ex) {
  51278. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  51279. }
  51280. }
  51281. var configFileUrl = jsonUrl + "/config.json";
  51282. var xhr = new XMLHttpRequest();
  51283. xhr.open("GET", configFileUrl, true);
  51284. xhr.addEventListener("load", function () {
  51285. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  51286. try {
  51287. _this._config = JSON.parse(xhr.response);
  51288. _this.updateShaderUniforms();
  51289. _this.updateTextures();
  51290. _this.setFragment(_this._texturePath + "/custom");
  51291. _this._animate = _this._config.animate;
  51292. _this.refreshRate = _this._config.refreshrate;
  51293. }
  51294. catch (ex) {
  51295. noConfigFile();
  51296. }
  51297. }
  51298. else {
  51299. noConfigFile();
  51300. }
  51301. }, false);
  51302. xhr.addEventListener("error", function () {
  51303. noConfigFile();
  51304. }, false);
  51305. try {
  51306. xhr.send();
  51307. }
  51308. catch (ex) {
  51309. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  51310. }
  51311. };
  51312. CustomProceduralTexture.prototype.isReady = function () {
  51313. if (!_super.prototype.isReady.call(this)) {
  51314. return false;
  51315. }
  51316. for (var name in this._textures) {
  51317. var texture = this._textures[name];
  51318. if (!texture.isReady()) {
  51319. return false;
  51320. }
  51321. }
  51322. return true;
  51323. };
  51324. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  51325. if (this._animate) {
  51326. this._time += this.getScene().getAnimationRatio() * 0.03;
  51327. this.updateShaderUniforms();
  51328. }
  51329. _super.prototype.render.call(this, useCameraPostProcess);
  51330. };
  51331. CustomProceduralTexture.prototype.updateTextures = function () {
  51332. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  51333. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  51334. }
  51335. };
  51336. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  51337. if (this._config) {
  51338. for (var j = 0; j < this._config.uniforms.length; j++) {
  51339. var uniform = this._config.uniforms[j];
  51340. switch (uniform.type) {
  51341. case "float":
  51342. this.setFloat(uniform.name, uniform.value);
  51343. break;
  51344. case "color3":
  51345. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  51346. break;
  51347. case "color4":
  51348. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  51349. break;
  51350. case "vector2":
  51351. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  51352. break;
  51353. case "vector3":
  51354. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  51355. break;
  51356. }
  51357. }
  51358. }
  51359. this.setFloat("time", this._time);
  51360. };
  51361. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  51362. get: function () {
  51363. return this._animate;
  51364. },
  51365. set: function (value) {
  51366. this._animate = value;
  51367. },
  51368. enumerable: true,
  51369. configurable: true
  51370. });
  51371. return CustomProceduralTexture;
  51372. }(BABYLON.ProceduralTexture));
  51373. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  51374. })(BABYLON || (BABYLON = {}));
  51375. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  51376. var BABYLON;
  51377. (function (BABYLON) {
  51378. var FreeCameraGamepadInput = (function () {
  51379. function FreeCameraGamepadInput() {
  51380. this.gamepadAngularSensibility = 200;
  51381. this.gamepadMoveSensibility = 40;
  51382. // private members
  51383. this._cameraTransform = BABYLON.Matrix.Identity();
  51384. this._deltaTransform = BABYLON.Vector3.Zero();
  51385. this._vector3 = BABYLON.Vector3.Zero();
  51386. this._vector2 = BABYLON.Vector2.Zero();
  51387. }
  51388. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  51389. var _this = this;
  51390. var manager = this.camera.getScene().gamepadManager;
  51391. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  51392. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  51393. // prioritize XBOX gamepads.
  51394. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  51395. _this.gamepad = gamepad;
  51396. }
  51397. }
  51398. });
  51399. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  51400. if (_this.gamepad === gamepad) {
  51401. _this.gamepad = null;
  51402. }
  51403. });
  51404. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  51405. };
  51406. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  51407. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  51408. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  51409. this.gamepad = null;
  51410. };
  51411. FreeCameraGamepadInput.prototype.checkInputs = function () {
  51412. if (this.gamepad && this.gamepad.leftStick) {
  51413. var camera = this.camera;
  51414. var LSValues = this.gamepad.leftStick;
  51415. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  51416. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  51417. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  51418. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  51419. var RSValues = this.gamepad.rightStick;
  51420. if (RSValues) {
  51421. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  51422. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  51423. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  51424. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  51425. }
  51426. else {
  51427. RSValues = { x: 0, y: 0 };
  51428. }
  51429. if (!camera.rotationQuaternion) {
  51430. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  51431. }
  51432. else {
  51433. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  51434. }
  51435. var speed = camera._computeLocalCameraSpeed() * 50.0;
  51436. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  51437. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  51438. camera.cameraDirection.addInPlace(this._deltaTransform);
  51439. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  51440. camera.cameraRotation.addInPlace(this._vector2);
  51441. }
  51442. };
  51443. FreeCameraGamepadInput.prototype.getClassName = function () {
  51444. return "FreeCameraGamepadInput";
  51445. };
  51446. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  51447. return "gamepad";
  51448. };
  51449. return FreeCameraGamepadInput;
  51450. }());
  51451. __decorate([
  51452. BABYLON.serialize()
  51453. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  51454. __decorate([
  51455. BABYLON.serialize()
  51456. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  51457. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  51458. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  51459. })(BABYLON || (BABYLON = {}));
  51460. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  51461. var BABYLON;
  51462. (function (BABYLON) {
  51463. var ArcRotateCameraGamepadInput = (function () {
  51464. function ArcRotateCameraGamepadInput() {
  51465. this.gamepadRotationSensibility = 80;
  51466. this.gamepadMoveSensibility = 40;
  51467. }
  51468. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  51469. var _this = this;
  51470. var manager = this.camera.getScene().gamepadManager;
  51471. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  51472. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  51473. // prioritize XBOX gamepads.
  51474. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  51475. _this.gamepad = gamepad;
  51476. }
  51477. }
  51478. });
  51479. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  51480. if (_this.gamepad === gamepad) {
  51481. _this.gamepad = null;
  51482. }
  51483. });
  51484. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  51485. };
  51486. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  51487. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  51488. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  51489. this.gamepad = null;
  51490. };
  51491. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  51492. if (this.gamepad) {
  51493. var camera = this.camera;
  51494. var RSValues = this.gamepad.rightStick;
  51495. if (RSValues) {
  51496. if (RSValues.x != 0) {
  51497. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  51498. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  51499. camera.inertialAlphaOffset += normalizedRX;
  51500. }
  51501. }
  51502. if (RSValues.y != 0) {
  51503. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  51504. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  51505. camera.inertialBetaOffset += normalizedRY;
  51506. }
  51507. }
  51508. }
  51509. var LSValues = this.gamepad.leftStick;
  51510. if (LSValues && LSValues.y != 0) {
  51511. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  51512. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  51513. this.camera.inertialRadiusOffset -= normalizedLY;
  51514. }
  51515. }
  51516. }
  51517. };
  51518. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  51519. return "ArcRotateCameraGamepadInput";
  51520. };
  51521. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  51522. return "gamepad";
  51523. };
  51524. return ArcRotateCameraGamepadInput;
  51525. }());
  51526. __decorate([
  51527. BABYLON.serialize()
  51528. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  51529. __decorate([
  51530. BABYLON.serialize()
  51531. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  51532. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  51533. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  51534. })(BABYLON || (BABYLON = {}));
  51535. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  51536. var BABYLON;
  51537. (function (BABYLON) {
  51538. var GamepadManager = (function () {
  51539. function GamepadManager() {
  51540. var _this = this;
  51541. this._babylonGamepads = [];
  51542. this._oneGamepadConnected = false;
  51543. this._isMonitoring = false;
  51544. this._gamepadEventSupported = 'GamepadEvent' in window;
  51545. this._gamepadSupport = (navigator.getGamepads ||
  51546. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  51547. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  51548. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  51549. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  51550. for (var i in _this._babylonGamepads) {
  51551. var gamepad = _this._babylonGamepads[i];
  51552. if (gamepad && gamepad._isConnected) {
  51553. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  51554. }
  51555. }
  51556. });
  51557. this._onGamepadConnectedEvent = function (evt) {
  51558. var gamepad = evt.gamepad;
  51559. if (gamepad.index in _this._babylonGamepads) {
  51560. if (_this._babylonGamepads[gamepad.index].isConnected) {
  51561. return;
  51562. }
  51563. }
  51564. var newGamepad;
  51565. if (_this._babylonGamepads[gamepad.index]) {
  51566. newGamepad = _this._babylonGamepads[gamepad.index];
  51567. newGamepad.browserGamepad = gamepad;
  51568. newGamepad._isConnected = true;
  51569. }
  51570. else {
  51571. newGamepad = _this._addNewGamepad(gamepad);
  51572. }
  51573. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  51574. _this._startMonitoringGamepads();
  51575. };
  51576. this._onGamepadDisconnectedEvent = function (evt) {
  51577. var gamepad = evt.gamepad;
  51578. // Remove the gamepad from the list of gamepads to monitor.
  51579. for (var i in _this._babylonGamepads) {
  51580. if (_this._babylonGamepads[i].index === gamepad.index) {
  51581. var disconnectedGamepad = _this._babylonGamepads[i];
  51582. disconnectedGamepad._isConnected = false;
  51583. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  51584. break;
  51585. }
  51586. }
  51587. };
  51588. if (this._gamepadSupport) {
  51589. //first add already-connected gamepads
  51590. this._updateGamepadObjects();
  51591. if (this._babylonGamepads.length) {
  51592. this._startMonitoringGamepads();
  51593. }
  51594. // Checking if the gamepad connected event is supported (like in Firefox)
  51595. if (this._gamepadEventSupported) {
  51596. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  51597. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  51598. }
  51599. else {
  51600. this._startMonitoringGamepads();
  51601. }
  51602. }
  51603. }
  51604. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  51605. get: function () {
  51606. return this._babylonGamepads;
  51607. },
  51608. enumerable: true,
  51609. configurable: true
  51610. });
  51611. GamepadManager.prototype.getGamepadByType = function (type) {
  51612. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  51613. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  51614. var gamepad = _a[_i];
  51615. if (gamepad && gamepad.type === type) {
  51616. return gamepad;
  51617. }
  51618. }
  51619. return null;
  51620. };
  51621. GamepadManager.prototype.dispose = function () {
  51622. if (this._gamepadEventSupported) {
  51623. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  51624. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  51625. this._onGamepadConnectedEvent = null;
  51626. this._onGamepadDisconnectedEvent = null;
  51627. }
  51628. this._babylonGamepads.forEach(function (gamepad) {
  51629. gamepad.dispose();
  51630. });
  51631. this.onGamepadConnectedObservable.clear();
  51632. this.onGamepadDisconnectedObservable.clear();
  51633. this._oneGamepadConnected = false;
  51634. this._stopMonitoringGamepads();
  51635. this._babylonGamepads = [];
  51636. };
  51637. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  51638. if (!this._oneGamepadConnected) {
  51639. this._oneGamepadConnected = true;
  51640. }
  51641. var newGamepad;
  51642. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  51643. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  51644. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  51645. }
  51646. else if (gamepad.pose) {
  51647. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  51648. }
  51649. else {
  51650. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  51651. }
  51652. this._babylonGamepads[newGamepad.index] = newGamepad;
  51653. return newGamepad;
  51654. };
  51655. GamepadManager.prototype._startMonitoringGamepads = function () {
  51656. if (!this._isMonitoring) {
  51657. this._isMonitoring = true;
  51658. this._checkGamepadsStatus();
  51659. }
  51660. };
  51661. GamepadManager.prototype._stopMonitoringGamepads = function () {
  51662. this._isMonitoring = false;
  51663. };
  51664. GamepadManager.prototype._checkGamepadsStatus = function () {
  51665. var _this = this;
  51666. // Hack to be compatible Chrome
  51667. this._updateGamepadObjects();
  51668. for (var i in this._babylonGamepads) {
  51669. var gamepad = this._babylonGamepads[i];
  51670. if (!gamepad || !gamepad.isConnected) {
  51671. continue;
  51672. }
  51673. gamepad.update();
  51674. }
  51675. if (this._isMonitoring) {
  51676. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  51677. }
  51678. };
  51679. // This function is called only on Chrome, which does not properly support
  51680. // connection/disconnection events and forces you to recopy again the gamepad object
  51681. GamepadManager.prototype._updateGamepadObjects = function () {
  51682. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  51683. for (var i = 0; i < gamepads.length; i++) {
  51684. if (gamepads[i]) {
  51685. if (!this._babylonGamepads[gamepads[i].index]) {
  51686. var newGamepad = this._addNewGamepad(gamepads[i]);
  51687. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  51688. }
  51689. else {
  51690. // Forced to copy again this object for Chrome for unknown reason
  51691. this._babylonGamepads[i].browserGamepad = gamepads[i];
  51692. if (!this._babylonGamepads[i].isConnected) {
  51693. this._babylonGamepads[i]._isConnected = true;
  51694. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  51695. }
  51696. }
  51697. }
  51698. }
  51699. };
  51700. return GamepadManager;
  51701. }());
  51702. BABYLON.GamepadManager = GamepadManager;
  51703. })(BABYLON || (BABYLON = {}));
  51704. //# sourceMappingURL=babylon.gamepadManager.js.map
  51705. var BABYLON;
  51706. (function (BABYLON) {
  51707. var StickValues = (function () {
  51708. function StickValues(x, y) {
  51709. this.x = x;
  51710. this.y = y;
  51711. }
  51712. return StickValues;
  51713. }());
  51714. BABYLON.StickValues = StickValues;
  51715. var Gamepad = (function () {
  51716. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  51717. if (leftStickX === void 0) { leftStickX = 0; }
  51718. if (leftStickY === void 0) { leftStickY = 1; }
  51719. if (rightStickX === void 0) { rightStickX = 2; }
  51720. if (rightStickY === void 0) { rightStickY = 3; }
  51721. this.id = id;
  51722. this.index = index;
  51723. this.browserGamepad = browserGamepad;
  51724. this._isConnected = true;
  51725. this.type = Gamepad.GAMEPAD;
  51726. this._leftStickAxisX = leftStickX;
  51727. this._leftStickAxisY = leftStickY;
  51728. this._rightStickAxisX = rightStickX;
  51729. this._rightStickAxisY = rightStickY;
  51730. if (this.browserGamepad.axes.length >= 2) {
  51731. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51732. }
  51733. if (this.browserGamepad.axes.length >= 4) {
  51734. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51735. }
  51736. }
  51737. Object.defineProperty(Gamepad.prototype, "isConnected", {
  51738. get: function () {
  51739. return this._isConnected;
  51740. },
  51741. enumerable: true,
  51742. configurable: true
  51743. });
  51744. Gamepad.prototype.onleftstickchanged = function (callback) {
  51745. this._onleftstickchanged = callback;
  51746. };
  51747. Gamepad.prototype.onrightstickchanged = function (callback) {
  51748. this._onrightstickchanged = callback;
  51749. };
  51750. Object.defineProperty(Gamepad.prototype, "leftStick", {
  51751. get: function () {
  51752. return this._leftStick;
  51753. },
  51754. set: function (newValues) {
  51755. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  51756. this._onleftstickchanged(newValues);
  51757. }
  51758. this._leftStick = newValues;
  51759. },
  51760. enumerable: true,
  51761. configurable: true
  51762. });
  51763. Object.defineProperty(Gamepad.prototype, "rightStick", {
  51764. get: function () {
  51765. return this._rightStick;
  51766. },
  51767. set: function (newValues) {
  51768. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  51769. this._onrightstickchanged(newValues);
  51770. }
  51771. this._rightStick = newValues;
  51772. },
  51773. enumerable: true,
  51774. configurable: true
  51775. });
  51776. Gamepad.prototype.update = function () {
  51777. if (this._leftStick) {
  51778. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51779. }
  51780. if (this._rightStick) {
  51781. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51782. }
  51783. };
  51784. Gamepad.prototype.dispose = function () {
  51785. };
  51786. return Gamepad;
  51787. }());
  51788. Gamepad.GAMEPAD = 0;
  51789. Gamepad.GENERIC = 1;
  51790. Gamepad.XBOX = 2;
  51791. Gamepad.POSE_ENABLED = 3;
  51792. BABYLON.Gamepad = Gamepad;
  51793. var GenericPad = (function (_super) {
  51794. __extends(GenericPad, _super);
  51795. function GenericPad(id, index, browserGamepad) {
  51796. var _this = _super.call(this, id, index, browserGamepad) || this;
  51797. _this.onButtonDownObservable = new BABYLON.Observable();
  51798. _this.onButtonUpObservable = new BABYLON.Observable();
  51799. _this.type = Gamepad.GENERIC;
  51800. _this._buttons = new Array(browserGamepad.buttons.length);
  51801. return _this;
  51802. }
  51803. GenericPad.prototype.onbuttondown = function (callback) {
  51804. this._onbuttondown = callback;
  51805. };
  51806. GenericPad.prototype.onbuttonup = function (callback) {
  51807. this._onbuttonup = callback;
  51808. };
  51809. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  51810. if (newValue !== currentValue) {
  51811. if (newValue === 1) {
  51812. if (this._onbuttondown) {
  51813. this._onbuttondown(buttonIndex);
  51814. }
  51815. this.onButtonDownObservable.notifyObservers(buttonIndex);
  51816. }
  51817. if (newValue === 0) {
  51818. if (this._onbuttonup) {
  51819. this._onbuttonup(buttonIndex);
  51820. }
  51821. this.onButtonUpObservable.notifyObservers(buttonIndex);
  51822. }
  51823. }
  51824. return newValue;
  51825. };
  51826. GenericPad.prototype.update = function () {
  51827. _super.prototype.update.call(this);
  51828. for (var index = 0; index < this._buttons.length; index++) {
  51829. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  51830. }
  51831. };
  51832. return GenericPad;
  51833. }(Gamepad));
  51834. BABYLON.GenericPad = GenericPad;
  51835. })(BABYLON || (BABYLON = {}));
  51836. //# sourceMappingURL=babylon.gamepad.js.map
  51837. var BABYLON;
  51838. (function (BABYLON) {
  51839. var Xbox360Button;
  51840. (function (Xbox360Button) {
  51841. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  51842. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  51843. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  51844. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  51845. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  51846. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  51847. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  51848. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  51849. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  51850. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  51851. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  51852. var Xbox360Dpad;
  51853. (function (Xbox360Dpad) {
  51854. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  51855. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  51856. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  51857. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  51858. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  51859. var Xbox360Pad = (function (_super) {
  51860. __extends(Xbox360Pad, _super);
  51861. function Xbox360Pad(id, index, gamepad, xboxOne) {
  51862. if (xboxOne === void 0) { xboxOne = false; }
  51863. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  51864. _this._leftTrigger = 0;
  51865. _this._rightTrigger = 0;
  51866. _this.onButtonDownObservable = new BABYLON.Observable();
  51867. _this.onButtonUpObservable = new BABYLON.Observable();
  51868. _this.onPadDownObservable = new BABYLON.Observable();
  51869. _this.onPadUpObservable = new BABYLON.Observable();
  51870. _this._buttonA = 0;
  51871. _this._buttonB = 0;
  51872. _this._buttonX = 0;
  51873. _this._buttonY = 0;
  51874. _this._buttonBack = 0;
  51875. _this._buttonStart = 0;
  51876. _this._buttonLB = 0;
  51877. _this._buttonRB = 0;
  51878. _this._buttonLeftStick = 0;
  51879. _this._buttonRightStick = 0;
  51880. _this._dPadUp = 0;
  51881. _this._dPadDown = 0;
  51882. _this._dPadLeft = 0;
  51883. _this._dPadRight = 0;
  51884. _this._isXboxOnePad = false;
  51885. _this.type = BABYLON.Gamepad.XBOX;
  51886. _this._isXboxOnePad = xboxOne;
  51887. return _this;
  51888. }
  51889. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  51890. this._onlefttriggerchanged = callback;
  51891. };
  51892. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  51893. this._onrighttriggerchanged = callback;
  51894. };
  51895. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  51896. get: function () {
  51897. return this._leftTrigger;
  51898. },
  51899. set: function (newValue) {
  51900. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  51901. this._onlefttriggerchanged(newValue);
  51902. }
  51903. this._leftTrigger = newValue;
  51904. },
  51905. enumerable: true,
  51906. configurable: true
  51907. });
  51908. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  51909. get: function () {
  51910. return this._rightTrigger;
  51911. },
  51912. set: function (newValue) {
  51913. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  51914. this._onrighttriggerchanged(newValue);
  51915. }
  51916. this._rightTrigger = newValue;
  51917. },
  51918. enumerable: true,
  51919. configurable: true
  51920. });
  51921. Xbox360Pad.prototype.onbuttondown = function (callback) {
  51922. this._onbuttondown = callback;
  51923. };
  51924. Xbox360Pad.prototype.onbuttonup = function (callback) {
  51925. this._onbuttonup = callback;
  51926. };
  51927. Xbox360Pad.prototype.ondpaddown = function (callback) {
  51928. this._ondpaddown = callback;
  51929. };
  51930. Xbox360Pad.prototype.ondpadup = function (callback) {
  51931. this._ondpadup = callback;
  51932. };
  51933. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  51934. if (newValue !== currentValue) {
  51935. if (newValue === 1) {
  51936. if (this._onbuttondown) {
  51937. this._onbuttondown(buttonType);
  51938. }
  51939. this.onButtonDownObservable.notifyObservers(buttonType);
  51940. }
  51941. if (newValue === 0) {
  51942. if (this._onbuttonup) {
  51943. this._onbuttonup(buttonType);
  51944. }
  51945. this.onButtonUpObservable.notifyObservers(buttonType);
  51946. }
  51947. }
  51948. return newValue;
  51949. };
  51950. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  51951. if (newValue !== currentValue) {
  51952. if (newValue === 1) {
  51953. if (this._ondpaddown) {
  51954. this._ondpaddown(buttonType);
  51955. }
  51956. this.onPadDownObservable.notifyObservers(buttonType);
  51957. }
  51958. if (newValue === 0) {
  51959. if (this._ondpadup) {
  51960. this._ondpadup(buttonType);
  51961. }
  51962. this.onPadUpObservable.notifyObservers(buttonType);
  51963. }
  51964. }
  51965. return newValue;
  51966. };
  51967. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  51968. get: function () {
  51969. return this._buttonA;
  51970. },
  51971. set: function (value) {
  51972. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  51973. },
  51974. enumerable: true,
  51975. configurable: true
  51976. });
  51977. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  51978. get: function () {
  51979. return this._buttonB;
  51980. },
  51981. set: function (value) {
  51982. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  51983. },
  51984. enumerable: true,
  51985. configurable: true
  51986. });
  51987. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  51988. get: function () {
  51989. return this._buttonX;
  51990. },
  51991. set: function (value) {
  51992. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  51993. },
  51994. enumerable: true,
  51995. configurable: true
  51996. });
  51997. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  51998. get: function () {
  51999. return this._buttonY;
  52000. },
  52001. set: function (value) {
  52002. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  52003. },
  52004. enumerable: true,
  52005. configurable: true
  52006. });
  52007. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  52008. get: function () {
  52009. return this._buttonStart;
  52010. },
  52011. set: function (value) {
  52012. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  52013. },
  52014. enumerable: true,
  52015. configurable: true
  52016. });
  52017. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  52018. get: function () {
  52019. return this._buttonBack;
  52020. },
  52021. set: function (value) {
  52022. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  52023. },
  52024. enumerable: true,
  52025. configurable: true
  52026. });
  52027. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  52028. get: function () {
  52029. return this._buttonLB;
  52030. },
  52031. set: function (value) {
  52032. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  52033. },
  52034. enumerable: true,
  52035. configurable: true
  52036. });
  52037. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  52038. get: function () {
  52039. return this._buttonRB;
  52040. },
  52041. set: function (value) {
  52042. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  52043. },
  52044. enumerable: true,
  52045. configurable: true
  52046. });
  52047. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  52048. get: function () {
  52049. return this._buttonLeftStick;
  52050. },
  52051. set: function (value) {
  52052. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  52053. },
  52054. enumerable: true,
  52055. configurable: true
  52056. });
  52057. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  52058. get: function () {
  52059. return this._buttonRightStick;
  52060. },
  52061. set: function (value) {
  52062. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  52063. },
  52064. enumerable: true,
  52065. configurable: true
  52066. });
  52067. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  52068. get: function () {
  52069. return this._dPadUp;
  52070. },
  52071. set: function (value) {
  52072. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  52073. },
  52074. enumerable: true,
  52075. configurable: true
  52076. });
  52077. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  52078. get: function () {
  52079. return this._dPadDown;
  52080. },
  52081. set: function (value) {
  52082. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  52083. },
  52084. enumerable: true,
  52085. configurable: true
  52086. });
  52087. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  52088. get: function () {
  52089. return this._dPadLeft;
  52090. },
  52091. set: function (value) {
  52092. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  52093. },
  52094. enumerable: true,
  52095. configurable: true
  52096. });
  52097. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  52098. get: function () {
  52099. return this._dPadRight;
  52100. },
  52101. set: function (value) {
  52102. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  52103. },
  52104. enumerable: true,
  52105. configurable: true
  52106. });
  52107. Xbox360Pad.prototype.update = function () {
  52108. _super.prototype.update.call(this);
  52109. if (this._isXboxOnePad) {
  52110. this.buttonA = this.browserGamepad.buttons[0].value;
  52111. this.buttonB = this.browserGamepad.buttons[1].value;
  52112. this.buttonX = this.browserGamepad.buttons[2].value;
  52113. this.buttonY = this.browserGamepad.buttons[3].value;
  52114. this.buttonLB = this.browserGamepad.buttons[4].value;
  52115. this.buttonRB = this.browserGamepad.buttons[5].value;
  52116. this.leftTrigger = this.browserGamepad.axes[2];
  52117. this.rightTrigger = this.browserGamepad.axes[5];
  52118. this.buttonBack = this.browserGamepad.buttons[9].value;
  52119. this.buttonStart = this.browserGamepad.buttons[8].value;
  52120. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  52121. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  52122. this.dPadUp = this.browserGamepad.buttons[11].value;
  52123. this.dPadDown = this.browserGamepad.buttons[12].value;
  52124. this.dPadLeft = this.browserGamepad.buttons[13].value;
  52125. this.dPadRight = this.browserGamepad.buttons[14].value;
  52126. }
  52127. else {
  52128. this.buttonA = this.browserGamepad.buttons[0].value;
  52129. this.buttonB = this.browserGamepad.buttons[1].value;
  52130. this.buttonX = this.browserGamepad.buttons[2].value;
  52131. this.buttonY = this.browserGamepad.buttons[3].value;
  52132. this.buttonLB = this.browserGamepad.buttons[4].value;
  52133. this.buttonRB = this.browserGamepad.buttons[5].value;
  52134. this.leftTrigger = this.browserGamepad.buttons[6].value;
  52135. this.rightTrigger = this.browserGamepad.buttons[7].value;
  52136. this.buttonBack = this.browserGamepad.buttons[8].value;
  52137. this.buttonStart = this.browserGamepad.buttons[9].value;
  52138. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  52139. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  52140. this.dPadUp = this.browserGamepad.buttons[12].value;
  52141. this.dPadDown = this.browserGamepad.buttons[13].value;
  52142. this.dPadLeft = this.browserGamepad.buttons[14].value;
  52143. this.dPadRight = this.browserGamepad.buttons[15].value;
  52144. }
  52145. };
  52146. return Xbox360Pad;
  52147. }(BABYLON.Gamepad));
  52148. BABYLON.Xbox360Pad = Xbox360Pad;
  52149. })(BABYLON || (BABYLON = {}));
  52150. //# sourceMappingURL=babylon.xboxGamepad.js.map
  52151. var BABYLON;
  52152. (function (BABYLON) {
  52153. var PoseEnabledControllerType;
  52154. (function (PoseEnabledControllerType) {
  52155. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  52156. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  52157. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  52158. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  52159. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  52160. var PoseEnabledControllerHelper = (function () {
  52161. function PoseEnabledControllerHelper() {
  52162. }
  52163. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  52164. // Oculus Touch
  52165. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  52166. return new BABYLON.OculusTouchController(vrGamepad);
  52167. }
  52168. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  52169. return new BABYLON.WindowsMotionController(vrGamepad);
  52170. }
  52171. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  52172. return new BABYLON.ViveController(vrGamepad);
  52173. }
  52174. else {
  52175. return new BABYLON.GenericController(vrGamepad);
  52176. }
  52177. };
  52178. return PoseEnabledControllerHelper;
  52179. }());
  52180. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  52181. var PoseEnabledController = (function (_super) {
  52182. __extends(PoseEnabledController, _super);
  52183. function PoseEnabledController(browserGamepad) {
  52184. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  52185. _this.deviceScaleFactor = 1;
  52186. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  52187. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  52188. _this.controllerType = PoseEnabledControllerType.GENERIC;
  52189. _this.position = BABYLON.Vector3.Zero();
  52190. _this.rotationQuaternion = new BABYLON.Quaternion();
  52191. _this.devicePosition = BABYLON.Vector3.Zero();
  52192. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  52193. _this._calculatedPosition = BABYLON.Vector3.Zero();
  52194. _this._calculatedRotation = new BABYLON.Quaternion();
  52195. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  52196. return _this;
  52197. }
  52198. PoseEnabledController.prototype.update = function () {
  52199. _super.prototype.update.call(this);
  52200. var pose = this.browserGamepad.pose;
  52201. this.updateFromDevice(pose);
  52202. if (this._mesh) {
  52203. this._mesh.position.copyFrom(this._calculatedPosition);
  52204. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  52205. }
  52206. };
  52207. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  52208. if (poseData) {
  52209. this.rawPose = poseData;
  52210. if (poseData.position) {
  52211. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  52212. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  52213. this.devicePosition.z *= -1;
  52214. }
  52215. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  52216. this._calculatedPosition.addInPlace(this.position);
  52217. }
  52218. if (poseData.orientation) {
  52219. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  52220. if (this._mesh) {
  52221. if (this._mesh.getScene().useRightHandedSystem) {
  52222. this.deviceRotationQuaternion.z *= -1;
  52223. this.deviceRotationQuaternion.w *= -1;
  52224. }
  52225. else {
  52226. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  52227. }
  52228. }
  52229. // if the camera is set, rotate to the camera's rotation
  52230. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  52231. }
  52232. }
  52233. };
  52234. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  52235. if (this._mesh) {
  52236. this._mesh.parent = undefined;
  52237. }
  52238. this._mesh = mesh;
  52239. if (this._poseControlledCamera) {
  52240. this._mesh.parent = this._poseControlledCamera;
  52241. }
  52242. if (!this._mesh.rotationQuaternion) {
  52243. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  52244. }
  52245. };
  52246. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  52247. this._poseControlledCamera = camera;
  52248. if (this._mesh) {
  52249. this._mesh.parent = this._poseControlledCamera;
  52250. }
  52251. };
  52252. PoseEnabledController.prototype.dispose = function () {
  52253. if (this._mesh) {
  52254. this._mesh.dispose();
  52255. }
  52256. this._mesh = undefined;
  52257. _super.prototype.dispose.call(this);
  52258. };
  52259. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  52260. get: function () {
  52261. return this._mesh;
  52262. },
  52263. enumerable: true,
  52264. configurable: true
  52265. });
  52266. PoseEnabledController.prototype.getForwardRay = function (length) {
  52267. if (length === void 0) { length = 100; }
  52268. if (!this.mesh) {
  52269. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  52270. }
  52271. var m = this.mesh.getWorldMatrix();
  52272. var origin = m.getTranslation();
  52273. var forward = new BABYLON.Vector3(0, 0, -1);
  52274. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  52275. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  52276. return new BABYLON.Ray(origin, direction, length);
  52277. };
  52278. return PoseEnabledController;
  52279. }(BABYLON.Gamepad));
  52280. BABYLON.PoseEnabledController = PoseEnabledController;
  52281. })(BABYLON || (BABYLON = {}));
  52282. //# sourceMappingURL=babylon.poseEnabledController.js.map
  52283. var BABYLON;
  52284. (function (BABYLON) {
  52285. var WebVRController = (function (_super) {
  52286. __extends(WebVRController, _super);
  52287. function WebVRController(vrGamepad) {
  52288. var _this = _super.call(this, vrGamepad) || this;
  52289. // Observables
  52290. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  52291. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  52292. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  52293. _this.onPadStateChangedObservable = new BABYLON.Observable();
  52294. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  52295. _this.pad = { x: 0, y: 0 };
  52296. // avoid GC, store state in a tmp object
  52297. _this._changes = {
  52298. pressChanged: false,
  52299. touchChanged: false,
  52300. valueChanged: false,
  52301. changed: false
  52302. };
  52303. _this._buttons = new Array(vrGamepad.buttons.length);
  52304. _this.hand = vrGamepad.hand;
  52305. return _this;
  52306. }
  52307. WebVRController.prototype.onButtonStateChange = function (callback) {
  52308. this._onButtonStateChange = callback;
  52309. };
  52310. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  52311. get: function () {
  52312. return this._defaultModel;
  52313. },
  52314. enumerable: true,
  52315. configurable: true
  52316. });
  52317. WebVRController.prototype.update = function () {
  52318. _super.prototype.update.call(this);
  52319. for (var index = 0; index < this._buttons.length; index++) {
  52320. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  52321. }
  52322. ;
  52323. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  52324. this.pad.x = this.leftStick.x;
  52325. this.pad.y = this.leftStick.y;
  52326. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  52327. }
  52328. };
  52329. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  52330. if (!newState) {
  52331. newState = {
  52332. pressed: false,
  52333. touched: false,
  52334. value: 0
  52335. };
  52336. }
  52337. if (!currentState) {
  52338. this._buttons[buttonIndex] = {
  52339. pressed: newState.pressed,
  52340. touched: newState.touched,
  52341. value: newState.value
  52342. };
  52343. return;
  52344. }
  52345. this._checkChanges(newState, currentState);
  52346. if (this._changes.changed) {
  52347. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  52348. this.handleButtonChange(buttonIndex, newState, this._changes);
  52349. }
  52350. this._buttons[buttonIndex].pressed = newState.pressed;
  52351. this._buttons[buttonIndex].touched = newState.touched;
  52352. // oculus triggers are never 0, thou not touched.
  52353. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  52354. };
  52355. WebVRController.prototype._checkChanges = function (newState, currentState) {
  52356. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  52357. this._changes.touchChanged = newState.touched !== currentState.touched;
  52358. this._changes.valueChanged = newState.value !== currentState.value;
  52359. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  52360. return this._changes;
  52361. };
  52362. WebVRController.prototype.dispose = function () {
  52363. _super.prototype.dispose.call(this);
  52364. this.onTriggerStateChangedObservable.clear();
  52365. this.onMainButtonStateChangedObservable.clear();
  52366. this.onSecondaryButtonStateChangedObservable.clear();
  52367. this.onPadStateChangedObservable.clear();
  52368. this.onPadValuesChangedObservable.clear();
  52369. };
  52370. return WebVRController;
  52371. }(BABYLON.PoseEnabledController));
  52372. BABYLON.WebVRController = WebVRController;
  52373. })(BABYLON || (BABYLON = {}));
  52374. //# sourceMappingURL=babylon.webVRController.js.map
  52375. var BABYLON;
  52376. (function (BABYLON) {
  52377. var OculusTouchController = (function (_super) {
  52378. __extends(OculusTouchController, _super);
  52379. function OculusTouchController(vrGamepad) {
  52380. var _this = _super.call(this, vrGamepad) || this;
  52381. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  52382. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  52383. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  52384. return _this;
  52385. }
  52386. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52387. var _this = this;
  52388. var meshName;
  52389. // Hand
  52390. if (this.hand === 'left') {
  52391. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  52392. }
  52393. else {
  52394. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  52395. }
  52396. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  52397. /*
  52398. Parent Mesh name: oculus_touch_left
  52399. - body
  52400. - trigger
  52401. - thumbstick
  52402. - grip
  52403. - button_y
  52404. - button_x
  52405. - button_enter
  52406. */
  52407. _this._defaultModel = newMeshes[1];
  52408. if (meshLoaded) {
  52409. meshLoaded(_this._defaultModel);
  52410. }
  52411. _this.attachToMesh(_this._defaultModel);
  52412. });
  52413. };
  52414. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  52415. // helper getters for left and right hand.
  52416. get: function () {
  52417. if (this.hand === 'right') {
  52418. return this.onMainButtonStateChangedObservable;
  52419. }
  52420. else {
  52421. throw new Error('No A button on left hand');
  52422. }
  52423. },
  52424. enumerable: true,
  52425. configurable: true
  52426. });
  52427. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  52428. get: function () {
  52429. if (this.hand === 'right') {
  52430. return this.onSecondaryButtonStateChangedObservable;
  52431. }
  52432. else {
  52433. throw new Error('No B button on left hand');
  52434. }
  52435. },
  52436. enumerable: true,
  52437. configurable: true
  52438. });
  52439. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  52440. get: function () {
  52441. if (this.hand === 'left') {
  52442. return this.onMainButtonStateChangedObservable;
  52443. }
  52444. else {
  52445. throw new Error('No X button on right hand');
  52446. }
  52447. },
  52448. enumerable: true,
  52449. configurable: true
  52450. });
  52451. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  52452. get: function () {
  52453. if (this.hand === 'left') {
  52454. return this.onSecondaryButtonStateChangedObservable;
  52455. }
  52456. else {
  52457. throw new Error('No Y button on right hand');
  52458. }
  52459. },
  52460. enumerable: true,
  52461. configurable: true
  52462. });
  52463. /*
  52464. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  52465. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  52466. 2) secondary trigger (same)
  52467. 3) A (right) X (left), touch, pressed = value
  52468. 4) B / Y
  52469. 5) thumb rest
  52470. */
  52471. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52472. var notifyObject = state; //{ state: state, changes: changes };
  52473. var triggerDirection = this.hand === 'right' ? -1 : 1;
  52474. switch (buttonIdx) {
  52475. case 0:
  52476. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  52477. return;
  52478. case 1:
  52479. if (this._defaultModel) {
  52480. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  52481. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  52482. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  52483. }
  52484. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  52485. return;
  52486. case 2:
  52487. if (this._defaultModel) {
  52488. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  52489. }
  52490. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  52491. return;
  52492. case 3:
  52493. if (this._defaultModel) {
  52494. if (notifyObject.pressed) {
  52495. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  52496. }
  52497. else {
  52498. (this._defaultModel.getChildren()[1]).position.y = 0;
  52499. }
  52500. }
  52501. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  52502. return;
  52503. case 4:
  52504. if (this._defaultModel) {
  52505. if (notifyObject.pressed) {
  52506. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  52507. }
  52508. else {
  52509. (this._defaultModel.getChildren()[2]).position.y = 0;
  52510. }
  52511. }
  52512. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  52513. return;
  52514. case 5:
  52515. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  52516. return;
  52517. }
  52518. };
  52519. return OculusTouchController;
  52520. }(BABYLON.WebVRController));
  52521. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  52522. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  52523. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  52524. BABYLON.OculusTouchController = OculusTouchController;
  52525. })(BABYLON || (BABYLON = {}));
  52526. //# sourceMappingURL=babylon.oculusTouchController.js.map
  52527. var BABYLON;
  52528. (function (BABYLON) {
  52529. var ViveController = (function (_super) {
  52530. __extends(ViveController, _super);
  52531. function ViveController(vrGamepad) {
  52532. var _this = _super.call(this, vrGamepad) || this;
  52533. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  52534. return _this;
  52535. }
  52536. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52537. var _this = this;
  52538. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  52539. /*
  52540. Parent Mesh name: ViveWand
  52541. - body
  52542. - r_gripper
  52543. - l_gripper
  52544. - menu_button
  52545. - system_button
  52546. - trackpad
  52547. - trigger
  52548. - LED
  52549. */
  52550. _this._defaultModel = newMeshes[1];
  52551. if (meshLoaded) {
  52552. meshLoaded(_this._defaultModel);
  52553. }
  52554. _this.attachToMesh(_this._defaultModel);
  52555. });
  52556. };
  52557. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  52558. get: function () {
  52559. return this.onMainButtonStateChangedObservable;
  52560. },
  52561. enumerable: true,
  52562. configurable: true
  52563. });
  52564. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  52565. get: function () {
  52566. return this.onMainButtonStateChangedObservable;
  52567. },
  52568. enumerable: true,
  52569. configurable: true
  52570. });
  52571. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  52572. get: function () {
  52573. return this.onSecondaryButtonStateChangedObservable;
  52574. },
  52575. enumerable: true,
  52576. configurable: true
  52577. });
  52578. /**
  52579. * Vive mapping:
  52580. * 0: touchpad
  52581. * 1: trigger
  52582. * 2: left AND right buttons
  52583. * 3: menu button
  52584. */
  52585. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52586. var notifyObject = state; //{ state: state, changes: changes };
  52587. switch (buttonIdx) {
  52588. case 0:
  52589. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  52590. return;
  52591. case 1:
  52592. if (this._defaultModel) {
  52593. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  52594. }
  52595. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  52596. return;
  52597. case 2:
  52598. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  52599. return;
  52600. case 3:
  52601. if (this._defaultModel) {
  52602. if (notifyObject.pressed) {
  52603. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  52604. }
  52605. else {
  52606. (this._defaultModel.getChildren()[2]).position.y = 0;
  52607. }
  52608. }
  52609. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  52610. return;
  52611. }
  52612. };
  52613. return ViveController;
  52614. }(BABYLON.WebVRController));
  52615. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  52616. ViveController.MODEL_FILENAME = 'wand.babylon';
  52617. BABYLON.ViveController = ViveController;
  52618. })(BABYLON || (BABYLON = {}));
  52619. //# sourceMappingURL=babylon.viveController.js.map
  52620. var BABYLON;
  52621. (function (BABYLON) {
  52622. var GenericController = (function (_super) {
  52623. __extends(GenericController, _super);
  52624. function GenericController(vrGamepad) {
  52625. return _super.call(this, vrGamepad) || this;
  52626. }
  52627. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52628. var _this = this;
  52629. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  52630. _this._defaultModel = newMeshes[1];
  52631. if (meshLoaded) {
  52632. meshLoaded(_this._defaultModel);
  52633. }
  52634. _this.attachToMesh(_this._defaultModel);
  52635. });
  52636. };
  52637. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52638. console.log("Button id: " + buttonIdx + "state: ");
  52639. console.dir(state);
  52640. };
  52641. return GenericController;
  52642. }(BABYLON.WebVRController));
  52643. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  52644. GenericController.MODEL_FILENAME = 'generic.babylon';
  52645. BABYLON.GenericController = GenericController;
  52646. })(BABYLON || (BABYLON = {}));
  52647. //# sourceMappingURL=babylon.genericController.js.map
  52648. var BABYLON;
  52649. (function (BABYLON) {
  52650. var LoadedMeshInfo = (function () {
  52651. function LoadedMeshInfo() {
  52652. this.buttonMeshes = {};
  52653. this.axisMeshes = {};
  52654. }
  52655. return LoadedMeshInfo;
  52656. }());
  52657. var WindowsMotionController = (function (_super) {
  52658. __extends(WindowsMotionController, _super);
  52659. function WindowsMotionController(vrGamepad) {
  52660. var _this = _super.call(this, vrGamepad) || this;
  52661. _this._mapping = {
  52662. // Semantic button names
  52663. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  52664. // A mapping of the button name to glTF model node name
  52665. // that should be transformed by button value.
  52666. buttonMeshNames: {
  52667. 'trigger': 'SELECT',
  52668. 'menu': 'MENU',
  52669. 'grip': 'GRASP',
  52670. 'thumbstick': 'THUMBSTICK_PRESS',
  52671. 'trackpad': 'TOUCHPAD_PRESS'
  52672. },
  52673. // This mapping is used to translate from the Motion Controller to Babylon semantics
  52674. buttonObservableNames: {
  52675. 'trigger': 'onTriggerStateChangedObservable',
  52676. 'menu': 'onSecondaryButtonStateChangedObservable',
  52677. 'grip': 'onMainButtonStateChangedObservable',
  52678. 'thumbstick': 'onPadStateChangedObservable',
  52679. 'trackpad': 'onTrackpadChangedObservable'
  52680. },
  52681. // A mapping of the axis name to glTF model node name
  52682. // that should be transformed by axis value.
  52683. // This array mirrors the browserGamepad.axes array, such that
  52684. // the mesh corresponding to axis 0 is in this array index 0.
  52685. axisMeshNames: [
  52686. 'THUMBSTICK_X',
  52687. 'THUMBSTICK_Y',
  52688. 'TOUCHPAD_TOUCH_X',
  52689. 'TOUCHPAD_TOUCH_Y'
  52690. ],
  52691. pointingPoseMeshName: 'POINTING_POSE'
  52692. };
  52693. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  52694. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  52695. _this._loadedMeshInfo = null;
  52696. return _this;
  52697. }
  52698. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  52699. get: function () {
  52700. return this.onTriggerStateChangedObservable;
  52701. },
  52702. enumerable: true,
  52703. configurable: true
  52704. });
  52705. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  52706. get: function () {
  52707. return this.onSecondaryButtonStateChangedObservable;
  52708. },
  52709. enumerable: true,
  52710. configurable: true
  52711. });
  52712. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  52713. get: function () {
  52714. return this.onMainButtonStateChangedObservable;
  52715. },
  52716. enumerable: true,
  52717. configurable: true
  52718. });
  52719. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  52720. get: function () {
  52721. return this.onPadStateChangedObservable;
  52722. },
  52723. enumerable: true,
  52724. configurable: true
  52725. });
  52726. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  52727. get: function () {
  52728. return this.onTrackpadChangedObservable;
  52729. },
  52730. enumerable: true,
  52731. configurable: true
  52732. });
  52733. /**
  52734. * Called once per frame by the engine.
  52735. */
  52736. WindowsMotionController.prototype.update = function () {
  52737. _super.prototype.update.call(this);
  52738. // Only need to animate axes if there is a loaded mesh
  52739. if (this._loadedMeshInfo) {
  52740. if (this.browserGamepad.axes) {
  52741. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  52742. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  52743. }
  52744. }
  52745. }
  52746. };
  52747. /**
  52748. * Called once for each button that changed state since the last frame
  52749. * @param buttonIdx Which button index changed
  52750. * @param state New state of the button
  52751. * @param changes Which properties on the state changed since last frame
  52752. */
  52753. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52754. var buttonName = this._mapping.buttons[buttonIdx];
  52755. if (!buttonName) {
  52756. return;
  52757. }
  52758. // Only emit events for buttons that we know how to map from index to name
  52759. var observable = this[this._mapping.buttonObservableNames[buttonName]];
  52760. if (observable) {
  52761. observable.notifyObservers(state);
  52762. }
  52763. this.lerpButtonTransform(buttonName, state.value);
  52764. };
  52765. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  52766. // If there is no loaded mesh, there is nothing to transform.
  52767. if (!this._loadedMeshInfo) {
  52768. return;
  52769. }
  52770. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  52771. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  52772. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  52773. };
  52774. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  52775. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  52776. if (!meshInfo) {
  52777. return;
  52778. }
  52779. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  52780. var lerpValue = axisValue * 0.5 + 0.5;
  52781. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  52782. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  52783. };
  52784. /**
  52785. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  52786. * @param scene scene in which to add meshes
  52787. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  52788. */
  52789. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  52790. var _this = this;
  52791. if (forceDefault === void 0) { forceDefault = false; }
  52792. var path;
  52793. var filename;
  52794. // Checking if GLB loader is present
  52795. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  52796. // Determine the device specific folder based on the ID suffix
  52797. var device = 'default';
  52798. if (this.id && !forceDefault) {
  52799. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  52800. device = ((match && match[0]) || device);
  52801. }
  52802. // Hand
  52803. if (this.hand === 'left') {
  52804. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  52805. }
  52806. else {
  52807. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  52808. }
  52809. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  52810. }
  52811. else {
  52812. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  52813. path = BABYLON.GenericController.MODEL_BASE_URL;
  52814. filename = BABYLON.GenericController.MODEL_FILENAME;
  52815. }
  52816. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  52817. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  52818. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  52819. if (!_this._loadedMeshInfo) {
  52820. return;
  52821. }
  52822. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  52823. _this.attachToMesh(_this._defaultModel);
  52824. if (meshLoaded) {
  52825. meshLoaded(_this._defaultModel);
  52826. }
  52827. }, null, function (scene, message) {
  52828. BABYLON.Tools.Log(message);
  52829. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  52830. if (!forceDefault) {
  52831. _this.initControllerMesh(scene, meshLoaded, true);
  52832. }
  52833. });
  52834. };
  52835. /**
  52836. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  52837. * can be transformed by button presses and axes values, based on this._mapping.
  52838. *
  52839. * @param scene scene in which the meshes exist
  52840. * @param meshes list of meshes that make up the controller model to process
  52841. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  52842. */
  52843. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  52844. var loadedMeshInfo = null;
  52845. // Create a new mesh to contain the glTF hierarchy
  52846. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  52847. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  52848. var childMesh = null;
  52849. for (var i = 0; i < meshes.length; i++) {
  52850. var mesh = meshes[i];
  52851. if (!mesh.parent) {
  52852. // Exclude controller meshes from picking results
  52853. mesh.isPickable = false;
  52854. // Handle root node, attach to the new parentMesh
  52855. childMesh = mesh;
  52856. break;
  52857. }
  52858. }
  52859. if (childMesh) {
  52860. childMesh.setParent(parentMesh);
  52861. // Create our mesh info. Note that this method will always return non-null.
  52862. loadedMeshInfo = this.createMeshInfo(parentMesh);
  52863. }
  52864. else {
  52865. BABYLON.Tools.Warn('Could not find root node in model file.');
  52866. }
  52867. return loadedMeshInfo;
  52868. };
  52869. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  52870. var loadedMeshInfo = new LoadedMeshInfo();
  52871. var i;
  52872. loadedMeshInfo.rootNode = rootNode;
  52873. // Reset the caches
  52874. loadedMeshInfo.buttonMeshes = {};
  52875. loadedMeshInfo.axisMeshes = {};
  52876. // Button Meshes
  52877. for (i = 0; i < this._mapping.buttons.length; i++) {
  52878. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  52879. if (!buttonMeshName) {
  52880. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  52881. continue;
  52882. }
  52883. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  52884. if (!buttonMesh) {
  52885. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  52886. continue;
  52887. }
  52888. var buttonMeshInfo = {
  52889. index: i,
  52890. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  52891. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  52892. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  52893. };
  52894. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  52895. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  52896. }
  52897. else {
  52898. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  52899. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  52900. '(VALUE: ' + !!buttonMeshInfo.value +
  52901. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  52902. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  52903. ')');
  52904. }
  52905. }
  52906. // Axis Meshes
  52907. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  52908. var axisMeshName = this._mapping.axisMeshNames[i];
  52909. if (!axisMeshName) {
  52910. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  52911. continue;
  52912. }
  52913. var axisMesh = getChildByName(rootNode, axisMeshName);
  52914. if (!axisMesh) {
  52915. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  52916. continue;
  52917. }
  52918. var axisMeshInfo = {
  52919. index: i,
  52920. value: getImmediateChildByName(axisMesh, 'VALUE'),
  52921. min: getImmediateChildByName(axisMesh, 'MIN'),
  52922. max: getImmediateChildByName(axisMesh, 'MAX')
  52923. };
  52924. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  52925. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  52926. }
  52927. else {
  52928. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  52929. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  52930. '(VALUE: ' + !!axisMeshInfo.value +
  52931. ', MIN: ' + !!axisMeshInfo.min +
  52932. ', MAX:' + !!axisMeshInfo.max +
  52933. ')');
  52934. }
  52935. }
  52936. // Pointing Ray
  52937. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  52938. if (!loadedMeshInfo.pointingPoseNode) {
  52939. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  52940. }
  52941. return loadedMeshInfo;
  52942. // Look through all children recursively. This will return null if no mesh exists with the given name.
  52943. function getChildByName(node, name) {
  52944. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  52945. }
  52946. // Look through only immediate children. This will return null if no mesh exists with the given name.
  52947. function getImmediateChildByName(node, name) {
  52948. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  52949. }
  52950. };
  52951. WindowsMotionController.prototype.getForwardRay = function (length) {
  52952. if (length === void 0) { length = 100; }
  52953. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  52954. return _super.prototype.getForwardRay.call(this, length);
  52955. }
  52956. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  52957. var origin = m.getTranslation();
  52958. var forward = new BABYLON.Vector3(0, 0, -1);
  52959. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  52960. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  52961. return new BABYLON.Ray(origin, direction, length);
  52962. };
  52963. WindowsMotionController.prototype.dispose = function () {
  52964. _super.prototype.dispose.call(this);
  52965. this.onTrackpadChangedObservable.clear();
  52966. };
  52967. return WindowsMotionController;
  52968. }(BABYLON.WebVRController));
  52969. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  52970. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  52971. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  52972. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  52973. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  52974. BABYLON.WindowsMotionController = WindowsMotionController;
  52975. })(BABYLON || (BABYLON = {}));
  52976. //# sourceMappingURL=babylon.windowsMotionController.js.map
  52977. /// <reference path="babylon.targetCamera.ts" />
  52978. var BABYLON;
  52979. (function (BABYLON) {
  52980. var FollowCamera = (function (_super) {
  52981. __extends(FollowCamera, _super);
  52982. function FollowCamera(name, position, scene, lockedTarget) {
  52983. var _this = _super.call(this, name, position, scene) || this;
  52984. _this.radius = 12;
  52985. _this.rotationOffset = 0;
  52986. _this.heightOffset = 4;
  52987. _this.cameraAcceleration = 0.05;
  52988. _this.maxCameraSpeed = 20;
  52989. _this.lockedTarget = lockedTarget;
  52990. return _this;
  52991. }
  52992. FollowCamera.prototype.getRadians = function (degrees) {
  52993. return degrees * Math.PI / 180;
  52994. };
  52995. FollowCamera.prototype.follow = function (cameraTarget) {
  52996. if (!cameraTarget)
  52997. return;
  52998. var yRotation;
  52999. if (cameraTarget.rotationQuaternion) {
  53000. var rotMatrix = new BABYLON.Matrix();
  53001. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  53002. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  53003. }
  53004. else {
  53005. yRotation = cameraTarget.rotation.y;
  53006. }
  53007. var radians = this.getRadians(this.rotationOffset) + yRotation;
  53008. var targetPosition = cameraTarget.getAbsolutePosition();
  53009. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  53010. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  53011. var dx = targetX - this.position.x;
  53012. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  53013. var dz = (targetZ) - this.position.z;
  53014. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  53015. var vy = dy * this.cameraAcceleration;
  53016. var vz = dz * this.cameraAcceleration * 2;
  53017. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  53018. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  53019. }
  53020. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  53021. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  53022. }
  53023. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  53024. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  53025. }
  53026. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  53027. this.setTarget(targetPosition);
  53028. };
  53029. FollowCamera.prototype._checkInputs = function () {
  53030. _super.prototype._checkInputs.call(this);
  53031. this.follow(this.lockedTarget);
  53032. };
  53033. FollowCamera.prototype.getClassName = function () {
  53034. return "FollowCamera";
  53035. };
  53036. return FollowCamera;
  53037. }(BABYLON.TargetCamera));
  53038. __decorate([
  53039. BABYLON.serialize()
  53040. ], FollowCamera.prototype, "radius", void 0);
  53041. __decorate([
  53042. BABYLON.serialize()
  53043. ], FollowCamera.prototype, "rotationOffset", void 0);
  53044. __decorate([
  53045. BABYLON.serialize()
  53046. ], FollowCamera.prototype, "heightOffset", void 0);
  53047. __decorate([
  53048. BABYLON.serialize()
  53049. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  53050. __decorate([
  53051. BABYLON.serialize()
  53052. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  53053. __decorate([
  53054. BABYLON.serializeAsMeshReference("lockedTargetId")
  53055. ], FollowCamera.prototype, "lockedTarget", void 0);
  53056. BABYLON.FollowCamera = FollowCamera;
  53057. var ArcFollowCamera = (function (_super) {
  53058. __extends(ArcFollowCamera, _super);
  53059. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  53060. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  53061. _this.alpha = alpha;
  53062. _this.beta = beta;
  53063. _this.radius = radius;
  53064. _this.target = target;
  53065. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  53066. _this.follow();
  53067. return _this;
  53068. }
  53069. ArcFollowCamera.prototype.follow = function () {
  53070. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  53071. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  53072. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  53073. var targetPosition = this.target.getAbsolutePosition();
  53074. this.position = targetPosition.add(this._cartesianCoordinates);
  53075. this.setTarget(targetPosition);
  53076. };
  53077. ArcFollowCamera.prototype._checkInputs = function () {
  53078. _super.prototype._checkInputs.call(this);
  53079. this.follow();
  53080. };
  53081. ArcFollowCamera.prototype.getClassName = function () {
  53082. return "ArcFollowCamera";
  53083. };
  53084. return ArcFollowCamera;
  53085. }(BABYLON.TargetCamera));
  53086. BABYLON.ArcFollowCamera = ArcFollowCamera;
  53087. })(BABYLON || (BABYLON = {}));
  53088. //# sourceMappingURL=babylon.followCamera.js.map
  53089. /// <reference path="babylon.touchCamera.ts" />
  53090. var BABYLON;
  53091. (function (BABYLON) {
  53092. // We're mainly based on the logic defined into the FreeCamera code
  53093. var UniversalCamera = (function (_super) {
  53094. __extends(UniversalCamera, _super);
  53095. //-- end properties for backward compatibility for inputs
  53096. function UniversalCamera(name, position, scene) {
  53097. var _this = _super.call(this, name, position, scene) || this;
  53098. _this.inputs.addGamepad();
  53099. return _this;
  53100. }
  53101. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  53102. //-- Begin properties for backward compatibility for inputs
  53103. get: function () {
  53104. var gamepad = this.inputs.attached["gamepad"];
  53105. if (gamepad)
  53106. return gamepad.gamepadAngularSensibility;
  53107. },
  53108. set: function (value) {
  53109. var gamepad = this.inputs.attached["gamepad"];
  53110. if (gamepad)
  53111. gamepad.gamepadAngularSensibility = value;
  53112. },
  53113. enumerable: true,
  53114. configurable: true
  53115. });
  53116. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  53117. get: function () {
  53118. var gamepad = this.inputs.attached["gamepad"];
  53119. if (gamepad)
  53120. return gamepad.gamepadMoveSensibility;
  53121. },
  53122. set: function (value) {
  53123. var gamepad = this.inputs.attached["gamepad"];
  53124. if (gamepad)
  53125. gamepad.gamepadMoveSensibility = value;
  53126. },
  53127. enumerable: true,
  53128. configurable: true
  53129. });
  53130. UniversalCamera.prototype.getClassName = function () {
  53131. return "UniversalCamera";
  53132. };
  53133. return UniversalCamera;
  53134. }(BABYLON.TouchCamera));
  53135. BABYLON.UniversalCamera = UniversalCamera;
  53136. })(BABYLON || (BABYLON = {}));
  53137. //# sourceMappingURL=babylon.universalCamera.js.map
  53138. /// <reference path="babylon.universalCamera.ts" />
  53139. var BABYLON;
  53140. (function (BABYLON) {
  53141. // We're mainly based on the logic defined into the FreeCamera code
  53142. var GamepadCamera = (function (_super) {
  53143. __extends(GamepadCamera, _super);
  53144. //-- end properties for backward compatibility for inputs
  53145. function GamepadCamera(name, position, scene) {
  53146. return _super.call(this, name, position, scene) || this;
  53147. }
  53148. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  53149. //-- Begin properties for backward compatibility for inputs
  53150. get: function () {
  53151. var gamepad = this.inputs.attached["gamepad"];
  53152. if (gamepad)
  53153. return gamepad.gamepadAngularSensibility;
  53154. },
  53155. set: function (value) {
  53156. var gamepad = this.inputs.attached["gamepad"];
  53157. if (gamepad)
  53158. gamepad.gamepadAngularSensibility = value;
  53159. },
  53160. enumerable: true,
  53161. configurable: true
  53162. });
  53163. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  53164. get: function () {
  53165. var gamepad = this.inputs.attached["gamepad"];
  53166. if (gamepad)
  53167. return gamepad.gamepadMoveSensibility;
  53168. },
  53169. set: function (value) {
  53170. var gamepad = this.inputs.attached["gamepad"];
  53171. if (gamepad)
  53172. gamepad.gamepadMoveSensibility = value;
  53173. },
  53174. enumerable: true,
  53175. configurable: true
  53176. });
  53177. GamepadCamera.prototype.getClassName = function () {
  53178. return "GamepadCamera";
  53179. };
  53180. return GamepadCamera;
  53181. }(BABYLON.UniversalCamera));
  53182. BABYLON.GamepadCamera = GamepadCamera;
  53183. })(BABYLON || (BABYLON = {}));
  53184. //# sourceMappingURL=babylon.gamepadCamera.js.map
  53185. var BABYLON;
  53186. (function (BABYLON) {
  53187. var PostProcessRenderPipelineManager = (function () {
  53188. function PostProcessRenderPipelineManager() {
  53189. this._renderPipelines = {};
  53190. }
  53191. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  53192. this._renderPipelines[renderPipeline._name] = renderPipeline;
  53193. };
  53194. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  53195. var renderPipeline = this._renderPipelines[renderPipelineName];
  53196. if (!renderPipeline) {
  53197. return;
  53198. }
  53199. renderPipeline._attachCameras(cameras, unique);
  53200. };
  53201. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  53202. var renderPipeline = this._renderPipelines[renderPipelineName];
  53203. if (!renderPipeline) {
  53204. return;
  53205. }
  53206. renderPipeline._detachCameras(cameras);
  53207. };
  53208. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  53209. var renderPipeline = this._renderPipelines[renderPipelineName];
  53210. if (!renderPipeline) {
  53211. return;
  53212. }
  53213. renderPipeline._enableEffect(renderEffectName, cameras);
  53214. };
  53215. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  53216. var renderPipeline = this._renderPipelines[renderPipelineName];
  53217. if (!renderPipeline) {
  53218. return;
  53219. }
  53220. renderPipeline._disableEffect(renderEffectName, cameras);
  53221. };
  53222. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  53223. var renderPipeline = this._renderPipelines[renderPipelineName];
  53224. if (!renderPipeline) {
  53225. return;
  53226. }
  53227. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  53228. };
  53229. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  53230. var renderPipeline = this._renderPipelines[renderPipelineName];
  53231. if (!renderPipeline) {
  53232. return;
  53233. }
  53234. renderPipeline._disableDisplayOnlyPass(cameras);
  53235. };
  53236. PostProcessRenderPipelineManager.prototype.update = function () {
  53237. for (var renderPipelineName in this._renderPipelines) {
  53238. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  53239. var pipeline = this._renderPipelines[renderPipelineName];
  53240. if (!pipeline.isSupported) {
  53241. pipeline.dispose();
  53242. delete this._renderPipelines[renderPipelineName];
  53243. }
  53244. else {
  53245. pipeline._update();
  53246. }
  53247. }
  53248. }
  53249. };
  53250. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  53251. for (var renderPipelineName in this._renderPipelines) {
  53252. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  53253. var pipeline = this._renderPipelines[renderPipelineName];
  53254. pipeline._rebuild();
  53255. }
  53256. }
  53257. };
  53258. PostProcessRenderPipelineManager.prototype.dispose = function () {
  53259. for (var renderPipelineName in this._renderPipelines) {
  53260. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  53261. var pipeline = this._renderPipelines[renderPipelineName];
  53262. pipeline.dispose();
  53263. }
  53264. }
  53265. };
  53266. return PostProcessRenderPipelineManager;
  53267. }());
  53268. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  53269. })(BABYLON || (BABYLON = {}));
  53270. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  53271. var BABYLON;
  53272. (function (BABYLON) {
  53273. var PostProcessRenderPass = (function () {
  53274. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  53275. this._enabled = true;
  53276. this._refCount = 0;
  53277. this._name = name;
  53278. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  53279. this.setRenderList(renderList);
  53280. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  53281. this._renderTexture.onAfterRenderObservable.add(afterRender);
  53282. this._scene = scene;
  53283. this._renderList = renderList;
  53284. }
  53285. // private
  53286. PostProcessRenderPass.prototype._incRefCount = function () {
  53287. if (this._refCount === 0) {
  53288. this._scene.customRenderTargets.push(this._renderTexture);
  53289. }
  53290. return ++this._refCount;
  53291. };
  53292. PostProcessRenderPass.prototype._decRefCount = function () {
  53293. this._refCount--;
  53294. if (this._refCount <= 0) {
  53295. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  53296. }
  53297. return this._refCount;
  53298. };
  53299. PostProcessRenderPass.prototype._update = function () {
  53300. this.setRenderList(this._renderList);
  53301. };
  53302. // public
  53303. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  53304. this._renderTexture.renderList = renderList;
  53305. };
  53306. PostProcessRenderPass.prototype.getRenderTexture = function () {
  53307. return this._renderTexture;
  53308. };
  53309. return PostProcessRenderPass;
  53310. }());
  53311. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  53312. })(BABYLON || (BABYLON = {}));
  53313. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  53314. var BABYLON;
  53315. (function (BABYLON) {
  53316. var PostProcessRenderEffect = (function () {
  53317. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  53318. this._engine = engine;
  53319. this._name = name;
  53320. this._singleInstance = singleInstance || true;
  53321. this._getPostProcess = getPostProcess;
  53322. this._cameras = [];
  53323. this._indicesForCamera = [];
  53324. this._postProcesses = {};
  53325. this._renderPasses = {};
  53326. this._renderEffectAsPasses = {};
  53327. }
  53328. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  53329. get: function () {
  53330. for (var index in this._postProcesses) {
  53331. if (!this._postProcesses[index].isSupported) {
  53332. return false;
  53333. }
  53334. }
  53335. return true;
  53336. },
  53337. enumerable: true,
  53338. configurable: true
  53339. });
  53340. PostProcessRenderEffect.prototype._update = function () {
  53341. for (var renderPassName in this._renderPasses) {
  53342. this._renderPasses[renderPassName]._update();
  53343. }
  53344. };
  53345. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  53346. this._renderPasses[renderPass._name] = renderPass;
  53347. this._linkParameters();
  53348. };
  53349. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  53350. delete this._renderPasses[renderPass._name];
  53351. this._linkParameters();
  53352. };
  53353. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  53354. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  53355. this._linkParameters();
  53356. };
  53357. PostProcessRenderEffect.prototype.getPass = function (passName) {
  53358. for (var renderPassName in this._renderPasses) {
  53359. if (renderPassName === passName) {
  53360. return this._renderPasses[passName];
  53361. }
  53362. }
  53363. };
  53364. PostProcessRenderEffect.prototype.emptyPasses = function () {
  53365. this._renderPasses = {};
  53366. this._linkParameters();
  53367. };
  53368. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  53369. var cameraKey;
  53370. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53371. for (var i = 0; i < _cam.length; i++) {
  53372. var camera = _cam[i];
  53373. var cameraName = camera.name;
  53374. if (this._singleInstance) {
  53375. cameraKey = 0;
  53376. }
  53377. else {
  53378. cameraKey = cameraName;
  53379. }
  53380. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  53381. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  53382. if (!this._indicesForCamera[cameraName]) {
  53383. this._indicesForCamera[cameraName] = [];
  53384. }
  53385. this._indicesForCamera[cameraName].push(index);
  53386. if (this._cameras.indexOf(camera) === -1) {
  53387. this._cameras[cameraName] = camera;
  53388. }
  53389. for (var passName in this._renderPasses) {
  53390. this._renderPasses[passName]._incRefCount();
  53391. }
  53392. }
  53393. this._linkParameters();
  53394. };
  53395. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  53396. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53397. for (var i = 0; i < _cam.length; i++) {
  53398. var camera = _cam[i];
  53399. var cameraName = camera.name;
  53400. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  53401. var index = this._cameras.indexOf(cameraName);
  53402. this._indicesForCamera.splice(index, 1);
  53403. this._cameras.splice(index, 1);
  53404. for (var passName in this._renderPasses) {
  53405. this._renderPasses[passName]._decRefCount();
  53406. }
  53407. }
  53408. };
  53409. PostProcessRenderEffect.prototype._enable = function (cameras) {
  53410. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53411. for (var i = 0; i < _cam.length; i++) {
  53412. var camera = _cam[i];
  53413. var cameraName = camera.name;
  53414. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  53415. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  53416. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  53417. }
  53418. }
  53419. for (var passName in this._renderPasses) {
  53420. this._renderPasses[passName]._incRefCount();
  53421. }
  53422. }
  53423. };
  53424. PostProcessRenderEffect.prototype._disable = function (cameras) {
  53425. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53426. for (var i = 0; i < _cam.length; i++) {
  53427. var camera = _cam[i];
  53428. var cameraName = camera.Name;
  53429. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  53430. for (var passName in this._renderPasses) {
  53431. this._renderPasses[passName]._decRefCount();
  53432. }
  53433. }
  53434. };
  53435. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  53436. if (this._singleInstance) {
  53437. return this._postProcesses[0];
  53438. }
  53439. else {
  53440. return this._postProcesses[camera.name];
  53441. }
  53442. };
  53443. PostProcessRenderEffect.prototype._linkParameters = function () {
  53444. var _this = this;
  53445. for (var index in this._postProcesses) {
  53446. if (this.applyParameters) {
  53447. this.applyParameters(this._postProcesses[index]);
  53448. }
  53449. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  53450. _this._linkTextures(effect);
  53451. });
  53452. }
  53453. };
  53454. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  53455. for (var renderPassName in this._renderPasses) {
  53456. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  53457. }
  53458. for (var renderEffectName in this._renderEffectAsPasses) {
  53459. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  53460. }
  53461. };
  53462. return PostProcessRenderEffect;
  53463. }());
  53464. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  53465. })(BABYLON || (BABYLON = {}));
  53466. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  53467. var BABYLON;
  53468. (function (BABYLON) {
  53469. var PostProcessRenderPipeline = (function () {
  53470. function PostProcessRenderPipeline(engine, name) {
  53471. this._engine = engine;
  53472. this._name = name;
  53473. this._renderEffects = new Array();
  53474. this._renderEffectsForIsolatedPass = new Array();
  53475. this._cameras = [];
  53476. }
  53477. PostProcessRenderPipeline.prototype.getClassName = function () {
  53478. return "PostProcessRenderPipeline";
  53479. };
  53480. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  53481. get: function () {
  53482. for (var renderEffectName in this._renderEffects) {
  53483. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53484. if (!this._renderEffects[renderEffectName].isSupported) {
  53485. return false;
  53486. }
  53487. }
  53488. }
  53489. return true;
  53490. },
  53491. enumerable: true,
  53492. configurable: true
  53493. });
  53494. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  53495. this._renderEffects[renderEffect._name] = renderEffect;
  53496. };
  53497. // private
  53498. PostProcessRenderPipeline.prototype._rebuild = function () {
  53499. };
  53500. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  53501. var renderEffects = this._renderEffects[renderEffectName];
  53502. if (!renderEffects) {
  53503. return;
  53504. }
  53505. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  53506. };
  53507. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  53508. var renderEffects = this._renderEffects[renderEffectName];
  53509. if (!renderEffects) {
  53510. return;
  53511. }
  53512. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  53513. };
  53514. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  53515. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53516. var indicesToDelete = [];
  53517. var i;
  53518. for (i = 0; i < _cam.length; i++) {
  53519. var camera = _cam[i];
  53520. var cameraName = camera.name;
  53521. if (this._cameras.indexOf(camera) === -1) {
  53522. this._cameras[cameraName] = camera;
  53523. }
  53524. else if (unique) {
  53525. indicesToDelete.push(i);
  53526. }
  53527. }
  53528. for (i = 0; i < indicesToDelete.length; i++) {
  53529. cameras.splice(indicesToDelete[i], 1);
  53530. }
  53531. for (var renderEffectName in this._renderEffects) {
  53532. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53533. this._renderEffects[renderEffectName]._attachCameras(_cam);
  53534. }
  53535. }
  53536. };
  53537. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  53538. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53539. for (var renderEffectName in this._renderEffects) {
  53540. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53541. this._renderEffects[renderEffectName]._detachCameras(_cam);
  53542. }
  53543. }
  53544. for (var i = 0; i < _cam.length; i++) {
  53545. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  53546. }
  53547. };
  53548. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  53549. var _this = this;
  53550. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53551. var pass = null;
  53552. var renderEffectName;
  53553. for (renderEffectName in this._renderEffects) {
  53554. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53555. pass = this._renderEffects[renderEffectName].getPass(passName);
  53556. if (pass != null) {
  53557. break;
  53558. }
  53559. }
  53560. }
  53561. if (pass === null) {
  53562. return;
  53563. }
  53564. for (renderEffectName in this._renderEffects) {
  53565. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53566. this._renderEffects[renderEffectName]._disable(_cam);
  53567. }
  53568. }
  53569. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  53570. for (var i = 0; i < _cam.length; i++) {
  53571. var camera = _cam[i];
  53572. var cameraName = camera.name;
  53573. 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); });
  53574. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  53575. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  53576. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  53577. }
  53578. };
  53579. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  53580. var _this = this;
  53581. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53582. for (var i = 0; i < _cam.length; i++) {
  53583. var camera = _cam[i];
  53584. var cameraName = camera.name;
  53585. 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); });
  53586. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  53587. }
  53588. for (var renderEffectName in this._renderEffects) {
  53589. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53590. this._renderEffects[renderEffectName]._enable(_cam);
  53591. }
  53592. }
  53593. };
  53594. PostProcessRenderPipeline.prototype._update = function () {
  53595. for (var renderEffectName in this._renderEffects) {
  53596. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53597. this._renderEffects[renderEffectName]._update();
  53598. }
  53599. }
  53600. for (var i = 0; i < this._cameras.length; i++) {
  53601. var cameraName = this._cameras[i].name;
  53602. if (this._renderEffectsForIsolatedPass[cameraName]) {
  53603. this._renderEffectsForIsolatedPass[cameraName]._update();
  53604. }
  53605. }
  53606. };
  53607. PostProcessRenderPipeline.prototype._reset = function () {
  53608. this._renderEffects = new Array();
  53609. this._renderEffectsForIsolatedPass = new Array();
  53610. };
  53611. PostProcessRenderPipeline.prototype.dispose = function () {
  53612. // Must be implemented by children
  53613. };
  53614. return PostProcessRenderPipeline;
  53615. }());
  53616. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  53617. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  53618. __decorate([
  53619. BABYLON.serialize()
  53620. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  53621. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  53622. })(BABYLON || (BABYLON = {}));
  53623. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  53624. var BABYLON;
  53625. (function (BABYLON) {
  53626. var DepthRenderer = (function () {
  53627. function DepthRenderer(scene, type) {
  53628. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  53629. var _this = this;
  53630. this._viewMatrix = BABYLON.Matrix.Zero();
  53631. this._projectionMatrix = BABYLON.Matrix.Zero();
  53632. this._transformMatrix = BABYLON.Matrix.Zero();
  53633. this._worldViewProjection = BABYLON.Matrix.Zero();
  53634. this._scene = scene;
  53635. var engine = scene.getEngine();
  53636. // Render target
  53637. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  53638. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53639. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53640. this._depthMap.refreshRate = 1;
  53641. this._depthMap.renderParticles = false;
  53642. this._depthMap.renderList = null;
  53643. // set default depth value to 1.0 (far away)
  53644. this._depthMap.onClearObservable.add(function (engine) {
  53645. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53646. });
  53647. // Custom render function
  53648. var renderSubMesh = function (subMesh) {
  53649. var mesh = subMesh.getRenderingMesh();
  53650. var scene = _this._scene;
  53651. var engine = scene.getEngine();
  53652. // Culling
  53653. engine.setState(subMesh.getMaterial().backFaceCulling);
  53654. // Managing instances
  53655. var batch = mesh._getInstancesRenderList(subMesh._id);
  53656. if (batch.mustReturn) {
  53657. return;
  53658. }
  53659. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  53660. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53661. engine.enableEffect(_this._effect);
  53662. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  53663. var material = subMesh.getMaterial();
  53664. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53665. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  53666. // Alpha test
  53667. if (material && material.needAlphaTesting()) {
  53668. var alphaTexture = material.getAlphaTestTexture();
  53669. _this._effect.setTexture("diffuseSampler", alphaTexture);
  53670. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53671. }
  53672. // Bones
  53673. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53674. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53675. }
  53676. // Draw
  53677. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53678. }
  53679. };
  53680. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  53681. var index;
  53682. if (depthOnlySubMeshes.length) {
  53683. engine.setColorWrite(false);
  53684. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  53685. renderSubMesh(depthOnlySubMeshes.data[index]);
  53686. }
  53687. engine.setColorWrite(true);
  53688. }
  53689. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53690. renderSubMesh(opaqueSubMeshes.data[index]);
  53691. }
  53692. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53693. renderSubMesh(alphaTestSubMeshes.data[index]);
  53694. }
  53695. };
  53696. }
  53697. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  53698. var material = subMesh.getMaterial();
  53699. if (material.disableDepthWrite) {
  53700. return false;
  53701. }
  53702. var defines = [];
  53703. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53704. var mesh = subMesh.getMesh();
  53705. var scene = mesh.getScene();
  53706. // Alpha test
  53707. if (material && material.needAlphaTesting()) {
  53708. defines.push("#define ALPHATEST");
  53709. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53710. attribs.push(BABYLON.VertexBuffer.UVKind);
  53711. defines.push("#define UV1");
  53712. }
  53713. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53714. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53715. defines.push("#define UV2");
  53716. }
  53717. }
  53718. // Bones
  53719. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53720. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53721. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53722. if (mesh.numBoneInfluencers > 4) {
  53723. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53724. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53725. }
  53726. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53727. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53728. }
  53729. else {
  53730. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53731. }
  53732. // Instances
  53733. if (useInstances) {
  53734. defines.push("#define INSTANCES");
  53735. attribs.push("world0");
  53736. attribs.push("world1");
  53737. attribs.push("world2");
  53738. attribs.push("world3");
  53739. }
  53740. // Get correct effect
  53741. var join = defines.join("\n");
  53742. if (this._cachedDefines !== join) {
  53743. this._cachedDefines = join;
  53744. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  53745. }
  53746. return this._effect.isReady();
  53747. };
  53748. DepthRenderer.prototype.getDepthMap = function () {
  53749. return this._depthMap;
  53750. };
  53751. // Methods
  53752. DepthRenderer.prototype.dispose = function () {
  53753. this._depthMap.dispose();
  53754. };
  53755. return DepthRenderer;
  53756. }());
  53757. BABYLON.DepthRenderer = DepthRenderer;
  53758. })(BABYLON || (BABYLON = {}));
  53759. //# sourceMappingURL=babylon.depthRenderer.js.map
  53760. var BABYLON;
  53761. (function (BABYLON) {
  53762. var SSAORenderingPipeline = (function (_super) {
  53763. __extends(SSAORenderingPipeline, _super);
  53764. /**
  53765. * @constructor
  53766. * @param {string} name - The rendering pipeline name
  53767. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53768. * @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 }
  53769. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53770. */
  53771. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  53772. var _this = _super.call(this, scene.getEngine(), name) || this;
  53773. // Members
  53774. /**
  53775. * The PassPostProcess id in the pipeline that contains the original scene color
  53776. * @type {string}
  53777. */
  53778. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53779. /**
  53780. * The SSAO PostProcess id in the pipeline
  53781. * @type {string}
  53782. */
  53783. _this.SSAORenderEffect = "SSAORenderEffect";
  53784. /**
  53785. * The horizontal blur PostProcess id in the pipeline
  53786. * @type {string}
  53787. */
  53788. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53789. /**
  53790. * The vertical blur PostProcess id in the pipeline
  53791. * @type {string}
  53792. */
  53793. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53794. /**
  53795. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53796. * @type {string}
  53797. */
  53798. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53799. /**
  53800. * The output strength of the SSAO post-process. Default value is 1.0.
  53801. * @type {number}
  53802. */
  53803. _this.totalStrength = 1.0;
  53804. /**
  53805. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  53806. * @type {number}
  53807. */
  53808. _this.radius = 0.0001;
  53809. /**
  53810. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  53811. * Must not be equal to fallOff and superior to fallOff.
  53812. * Default value is 0.975
  53813. * @type {number}
  53814. */
  53815. _this.area = 0.0075;
  53816. /**
  53817. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  53818. * Must not be equal to area and inferior to area.
  53819. * Default value is 0.0
  53820. * @type {number}
  53821. */
  53822. _this.fallOff = 0.000001;
  53823. /**
  53824. * The base color of the SSAO post-process
  53825. * The final result is "base + ssao" between [0, 1]
  53826. * @type {number}
  53827. */
  53828. _this.base = 0.5;
  53829. _this._firstUpdate = true;
  53830. _this._scene = scene;
  53831. // Set up assets
  53832. _this._createRandomTexture();
  53833. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53834. var ssaoRatio = ratio.ssaoRatio || ratio;
  53835. var combineRatio = ratio.combineRatio || ratio;
  53836. _this._ratio = {
  53837. ssaoRatio: ssaoRatio,
  53838. combineRatio: combineRatio
  53839. };
  53840. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53841. _this._createSSAOPostProcess(ssaoRatio);
  53842. _this._createBlurPostProcess(ssaoRatio);
  53843. _this._createSSAOCombinePostProcess(combineRatio);
  53844. // Set up pipeline
  53845. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53846. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53847. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53848. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53849. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53850. // Finish
  53851. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53852. if (cameras)
  53853. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53854. return _this;
  53855. }
  53856. // Public Methods
  53857. /**
  53858. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53859. */
  53860. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53861. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53862. for (var i = 0; i < this._scene.cameras.length; i++) {
  53863. var camera = this._scene.cameras[i];
  53864. this._originalColorPostProcess.dispose(camera);
  53865. this._ssaoPostProcess.dispose(camera);
  53866. this._blurHPostProcess.dispose(camera);
  53867. this._blurVPostProcess.dispose(camera);
  53868. this._ssaoCombinePostProcess.dispose(camera);
  53869. }
  53870. this._randomTexture.dispose();
  53871. if (disableDepthRender)
  53872. this._scene.disableDepthRenderer();
  53873. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53874. _super.prototype.dispose.call(this);
  53875. };
  53876. // Private Methods
  53877. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  53878. var _this = this;
  53879. /*
  53880. var samplerOffsets = [
  53881. -8.0, -6.0, -4.0, -2.0,
  53882. 0.0,
  53883. 2.0, 4.0, 6.0, 8.0
  53884. ];
  53885. */
  53886. var samples = 16;
  53887. var samplerOffsets = [];
  53888. for (var i = -8; i < 8; i++) {
  53889. samplerOffsets.push(i * 2);
  53890. }
  53891. 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");
  53892. this._blurHPostProcess.onApply = function (effect) {
  53893. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53894. effect.setTexture("depthSampler", _this._depthTexture);
  53895. if (_this._firstUpdate) {
  53896. effect.setArray("samplerOffsets", samplerOffsets);
  53897. }
  53898. };
  53899. 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");
  53900. this._blurVPostProcess.onApply = function (effect) {
  53901. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53902. effect.setTexture("depthSampler", _this._depthTexture);
  53903. if (_this._firstUpdate) {
  53904. effect.setArray("samplerOffsets", samplerOffsets);
  53905. _this._firstUpdate = false;
  53906. }
  53907. };
  53908. };
  53909. SSAORenderingPipeline.prototype._rebuild = function () {
  53910. this._firstUpdate = true;
  53911. _super.prototype._rebuild.call(this);
  53912. };
  53913. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53914. var _this = this;
  53915. var numSamples = 16;
  53916. var sampleSphere = [
  53917. 0.5381, 0.1856, -0.4319,
  53918. 0.1379, 0.2486, 0.4430,
  53919. 0.3371, 0.5679, -0.0057,
  53920. -0.6999, -0.0451, -0.0019,
  53921. 0.0689, -0.1598, -0.8547,
  53922. 0.0560, 0.0069, -0.1843,
  53923. -0.0146, 0.1402, 0.0762,
  53924. 0.0100, -0.1924, -0.0344,
  53925. -0.3577, -0.5301, -0.4358,
  53926. -0.3169, 0.1063, 0.0158,
  53927. 0.0103, -0.5869, 0.0046,
  53928. -0.0897, -0.4940, 0.3287,
  53929. 0.7119, -0.0154, -0.0918,
  53930. -0.0533, 0.0596, -0.5411,
  53931. 0.0352, -0.0631, 0.5460,
  53932. -0.4776, 0.2847, -0.0271
  53933. ];
  53934. var samplesFactor = 1.0 / numSamples;
  53935. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  53936. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53937. "area", "fallOff", "base", "range", "viewport"
  53938. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53939. var viewport = new BABYLON.Vector2(0, 0);
  53940. this._ssaoPostProcess.onApply = function (effect) {
  53941. if (_this._firstUpdate) {
  53942. effect.setArray3("sampleSphere", sampleSphere);
  53943. effect.setFloat("samplesFactor", samplesFactor);
  53944. effect.setFloat("randTextureTiles", 4.0);
  53945. }
  53946. effect.setFloat("totalStrength", _this.totalStrength);
  53947. effect.setFloat("radius", _this.radius);
  53948. effect.setFloat("area", _this.area);
  53949. effect.setFloat("fallOff", _this.fallOff);
  53950. effect.setFloat("base", _this.base);
  53951. effect.setTexture("textureSampler", _this._depthTexture);
  53952. effect.setTexture("randomSampler", _this._randomTexture);
  53953. };
  53954. };
  53955. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53956. var _this = this;
  53957. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53958. this._ssaoCombinePostProcess.onApply = function (effect) {
  53959. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53960. };
  53961. };
  53962. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  53963. var size = 512;
  53964. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53965. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53966. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53967. var context = this._randomTexture.getContext();
  53968. var rand = function (min, max) {
  53969. return Math.random() * (max - min) + min;
  53970. };
  53971. var randVector = BABYLON.Vector3.Zero();
  53972. for (var x = 0; x < size; x++) {
  53973. for (var y = 0; y < size; y++) {
  53974. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  53975. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  53976. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  53977. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53978. context.fillRect(x, y, 1, 1);
  53979. }
  53980. }
  53981. this._randomTexture.update(false);
  53982. };
  53983. return SSAORenderingPipeline;
  53984. }(BABYLON.PostProcessRenderPipeline));
  53985. __decorate([
  53986. BABYLON.serialize()
  53987. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  53988. __decorate([
  53989. BABYLON.serialize()
  53990. ], SSAORenderingPipeline.prototype, "radius", void 0);
  53991. __decorate([
  53992. BABYLON.serialize()
  53993. ], SSAORenderingPipeline.prototype, "area", void 0);
  53994. __decorate([
  53995. BABYLON.serialize()
  53996. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  53997. __decorate([
  53998. BABYLON.serialize()
  53999. ], SSAORenderingPipeline.prototype, "base", void 0);
  54000. __decorate([
  54001. BABYLON.serialize()
  54002. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  54003. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  54004. })(BABYLON || (BABYLON = {}));
  54005. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  54006. var BABYLON;
  54007. (function (BABYLON) {
  54008. var SSAO2RenderingPipeline = (function (_super) {
  54009. __extends(SSAO2RenderingPipeline, _super);
  54010. /**
  54011. * @constructor
  54012. * @param {string} name - The rendering pipeline name
  54013. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54014. * @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 }
  54015. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54016. */
  54017. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  54018. var _this = _super.call(this, scene.getEngine(), name) || this;
  54019. // Members
  54020. /**
  54021. * The PassPostProcess id in the pipeline that contains the original scene color
  54022. * @type {string}
  54023. */
  54024. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  54025. /**
  54026. * The SSAO PostProcess id in the pipeline
  54027. * @type {string}
  54028. */
  54029. _this.SSAORenderEffect = "SSAORenderEffect";
  54030. /**
  54031. * The horizontal blur PostProcess id in the pipeline
  54032. * @type {string}
  54033. */
  54034. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  54035. /**
  54036. * The vertical blur PostProcess id in the pipeline
  54037. * @type {string}
  54038. */
  54039. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  54040. /**
  54041. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  54042. * @type {string}
  54043. */
  54044. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  54045. /**
  54046. * The output strength of the SSAO post-process. Default value is 1.0.
  54047. * @type {number}
  54048. */
  54049. _this.totalStrength = 1.0;
  54050. /**
  54051. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  54052. * @type {number}
  54053. */
  54054. _this.maxZ = 100.0;
  54055. /**
  54056. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  54057. * @type {number}
  54058. */
  54059. _this.minZAspect = 0.2;
  54060. /**
  54061. * Number of samples used for the SSAO calculations. Default value is 8
  54062. * @type {number}
  54063. */
  54064. _this._samples = 8;
  54065. /**
  54066. * Are we using bilateral blur ?
  54067. * @type {boolean}
  54068. */
  54069. _this._expensiveBlur = true;
  54070. /**
  54071. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  54072. * @type {number}
  54073. */
  54074. _this.radius = 2.0;
  54075. /**
  54076. * The base color of the SSAO post-process
  54077. * The final result is "base + ssao" between [0, 1]
  54078. * @type {number}
  54079. */
  54080. _this.base = 0.1;
  54081. _this._firstUpdate = true;
  54082. _this._scene = scene;
  54083. if (!_this.isSupported) {
  54084. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  54085. return _this;
  54086. }
  54087. var ssaoRatio = ratio.ssaoRatio || ratio;
  54088. var blurRatio = ratio.blurRatio || ratio;
  54089. _this._ratio = {
  54090. ssaoRatio: ssaoRatio,
  54091. blurRatio: blurRatio
  54092. };
  54093. // Set up assets
  54094. _this._createRandomTexture();
  54095. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  54096. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  54097. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  54098. _this._createSSAOPostProcess(1.0);
  54099. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  54100. _this._createSSAOCombinePostProcess(blurRatio);
  54101. // Set up pipeline
  54102. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  54103. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  54104. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  54105. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  54106. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  54107. // Finish
  54108. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54109. if (cameras)
  54110. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54111. return _this;
  54112. }
  54113. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  54114. get: function () {
  54115. return this._samples;
  54116. },
  54117. set: function (n) {
  54118. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  54119. this._samples = n;
  54120. this._sampleSphere = this._generateHemisphere();
  54121. this._firstUpdate = true;
  54122. },
  54123. enumerable: true,
  54124. configurable: true
  54125. });
  54126. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  54127. get: function () {
  54128. return this._expensiveBlur;
  54129. },
  54130. set: function (b) {
  54131. 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"]);
  54132. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  54133. this._expensiveBlur = b;
  54134. this._firstUpdate = true;
  54135. },
  54136. enumerable: true,
  54137. configurable: true
  54138. });
  54139. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  54140. /**
  54141. * Support test.
  54142. * @type {boolean}
  54143. */
  54144. get: function () {
  54145. var engine = BABYLON.Engine.LastCreatedEngine;
  54146. return engine.getCaps().drawBuffersExtension;
  54147. },
  54148. enumerable: true,
  54149. configurable: true
  54150. });
  54151. // Public Methods
  54152. /**
  54153. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  54154. */
  54155. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  54156. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  54157. for (var i = 0; i < this._scene.cameras.length; i++) {
  54158. var camera = this._scene.cameras[i];
  54159. this._originalColorPostProcess.dispose(camera);
  54160. this._ssaoPostProcess.dispose(camera);
  54161. this._blurHPostProcess.dispose(camera);
  54162. this._blurVPostProcess.dispose(camera);
  54163. this._ssaoCombinePostProcess.dispose(camera);
  54164. }
  54165. this._randomTexture.dispose();
  54166. if (disableGeometryBufferRenderer)
  54167. this._scene.disableGeometryBufferRenderer();
  54168. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54169. _super.prototype.dispose.call(this);
  54170. };
  54171. // Private Methods
  54172. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  54173. var _this = this;
  54174. var samples = 16;
  54175. this._samplerOffsets = [];
  54176. var expensive = this.expensiveBlur;
  54177. for (var i = -8; i < 8; i++) {
  54178. this._samplerOffsets.push(i * 2 + 0.5);
  54179. }
  54180. 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");
  54181. this._blurHPostProcess.onApply = function (effect) {
  54182. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  54183. effect.setFloat("near", _this._scene.activeCamera.minZ);
  54184. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  54185. effect.setFloat("radius", _this.radius);
  54186. effect.setTexture("depthSampler", _this._depthTexture);
  54187. if (_this._firstUpdate) {
  54188. effect.setArray("samplerOffsets", _this._samplerOffsets);
  54189. }
  54190. };
  54191. 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");
  54192. this._blurVPostProcess.onApply = function (effect) {
  54193. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  54194. effect.setFloat("near", _this._scene.activeCamera.minZ);
  54195. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  54196. effect.setFloat("radius", _this.radius);
  54197. effect.setTexture("depthSampler", _this._depthTexture);
  54198. if (_this._firstUpdate) {
  54199. effect.setArray("samplerOffsets", _this._samplerOffsets);
  54200. _this._firstUpdate = false;
  54201. }
  54202. };
  54203. };
  54204. SSAO2RenderingPipeline.prototype._rebuild = function () {
  54205. this._firstUpdate = true;
  54206. _super.prototype._rebuild.call(this);
  54207. };
  54208. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  54209. var numSamples = this.samples;
  54210. var result = [];
  54211. var vector, scale;
  54212. var rand = function (min, max) {
  54213. return Math.random() * (max - min) + min;
  54214. };
  54215. var lerp = function (start, end, percent) {
  54216. return (start + percent * (end - start));
  54217. };
  54218. var i = 0;
  54219. var normal = new BABYLON.Vector3(0, 0, 1);
  54220. while (i < numSamples) {
  54221. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  54222. vector.normalize();
  54223. scale = i / numSamples;
  54224. scale = lerp(0.1, 1.0, scale * scale);
  54225. vector.scaleInPlace(scale);
  54226. result.push(vector.x, vector.y, vector.z);
  54227. i++;
  54228. }
  54229. return result;
  54230. };
  54231. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  54232. var _this = this;
  54233. var numSamples = this.samples;
  54234. this._sampleSphere = this._generateHemisphere();
  54235. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  54236. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  54237. "base", "range", "projection", "near", "far", "texelSize",
  54238. "xViewport", "yViewport", "maxZ", "minZAspect"
  54239. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  54240. this._ssaoPostProcess.onApply = function (effect) {
  54241. if (_this._firstUpdate) {
  54242. effect.setArray3("sampleSphere", _this._sampleSphere);
  54243. effect.setFloat("randTextureTiles", 4.0);
  54244. }
  54245. effect.setFloat("samplesFactor", 1 / _this.samples);
  54246. effect.setFloat("totalStrength", _this.totalStrength);
  54247. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  54248. effect.setFloat("radius", _this.radius);
  54249. effect.setFloat("maxZ", _this.maxZ);
  54250. effect.setFloat("minZAspect", _this.minZAspect);
  54251. effect.setFloat("base", _this.base);
  54252. effect.setFloat("near", _this._scene.activeCamera.minZ);
  54253. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  54254. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  54255. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  54256. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  54257. effect.setTexture("textureSampler", _this._depthTexture);
  54258. effect.setTexture("normalSampler", _this._normalTexture);
  54259. effect.setTexture("randomSampler", _this._randomTexture);
  54260. };
  54261. };
  54262. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  54263. var _this = this;
  54264. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54265. this._ssaoCombinePostProcess.onApply = function (effect) {
  54266. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  54267. };
  54268. };
  54269. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  54270. var size = 512;
  54271. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54272. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54273. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54274. var context = this._randomTexture.getContext();
  54275. var rand = function (min, max) {
  54276. return Math.random() * (max - min) + min;
  54277. };
  54278. var randVector = BABYLON.Vector3.Zero();
  54279. for (var x = 0; x < size; x++) {
  54280. for (var y = 0; y < size; y++) {
  54281. randVector.x = rand(0.0, 1.0);
  54282. randVector.y = rand(0.0, 1.0);
  54283. randVector.z = 0.0;
  54284. randVector.normalize();
  54285. randVector.scaleInPlace(255);
  54286. randVector.x = Math.floor(randVector.x);
  54287. randVector.y = Math.floor(randVector.y);
  54288. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  54289. context.fillRect(x, y, 1, 1);
  54290. }
  54291. }
  54292. this._randomTexture.update(false);
  54293. };
  54294. return SSAO2RenderingPipeline;
  54295. }(BABYLON.PostProcessRenderPipeline));
  54296. __decorate([
  54297. BABYLON.serialize()
  54298. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  54299. __decorate([
  54300. BABYLON.serialize()
  54301. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  54302. __decorate([
  54303. BABYLON.serialize()
  54304. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  54305. __decorate([
  54306. BABYLON.serialize("samples")
  54307. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  54308. __decorate([
  54309. BABYLON.serialize("expensiveBlur")
  54310. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  54311. __decorate([
  54312. BABYLON.serialize()
  54313. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  54314. __decorate([
  54315. BABYLON.serialize()
  54316. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  54317. __decorate([
  54318. BABYLON.serialize()
  54319. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  54320. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  54321. })(BABYLON || (BABYLON = {}));
  54322. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  54323. // BABYLON.JS Chromatic Aberration GLSL Shader
  54324. // Author: Olivier Guyot
  54325. // Separates very slightly R, G and B colors on the edges of the screen
  54326. // Inspired by Francois Tarlier & Martins Upitis
  54327. var BABYLON;
  54328. (function (BABYLON) {
  54329. var LensRenderingPipeline = (function (_super) {
  54330. __extends(LensRenderingPipeline, _super);
  54331. /**
  54332. * @constructor
  54333. *
  54334. * Effect parameters are as follow:
  54335. * {
  54336. * chromatic_aberration: number; // from 0 to x (1 for realism)
  54337. * edge_blur: number; // from 0 to x (1 for realism)
  54338. * distortion: number; // from 0 to x (1 for realism)
  54339. * grain_amount: number; // from 0 to 1
  54340. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  54341. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  54342. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  54343. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  54344. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  54345. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  54346. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  54347. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  54348. * }
  54349. * Note: if an effect parameter is unset, effect is disabled
  54350. *
  54351. * @param {string} name - The rendering pipeline name
  54352. * @param {object} parameters - An object containing all parameters (see above)
  54353. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54354. * @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)
  54355. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54356. */
  54357. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  54358. if (ratio === void 0) { ratio = 1.0; }
  54359. var _this = _super.call(this, scene.getEngine(), name) || this;
  54360. // Lens effects can be of the following:
  54361. // - chromatic aberration (slight shift of RGB colors)
  54362. // - blur on the edge of the lens
  54363. // - lens distortion
  54364. // - depth-of-field blur & highlights enhancing
  54365. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  54366. // - grain effect (noise or custom texture)
  54367. // Two additional texture samplers are needed:
  54368. // - depth map (for depth-of-field)
  54369. // - grain texture
  54370. /**
  54371. * The chromatic aberration PostProcess id in the pipeline
  54372. * @type {string}
  54373. */
  54374. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  54375. /**
  54376. * The highlights enhancing PostProcess id in the pipeline
  54377. * @type {string}
  54378. */
  54379. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  54380. /**
  54381. * The depth-of-field PostProcess id in the pipeline
  54382. * @type {string}
  54383. */
  54384. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  54385. _this._scene = scene;
  54386. // Fetch texture samplers
  54387. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  54388. if (parameters.grain_texture) {
  54389. _this._grainTexture = parameters.grain_texture;
  54390. }
  54391. else {
  54392. _this._createGrainTexture();
  54393. }
  54394. // save parameters
  54395. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  54396. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  54397. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  54398. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  54399. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  54400. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  54401. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  54402. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  54403. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  54404. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  54405. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  54406. // Create effects
  54407. _this._createChromaticAberrationPostProcess(ratio);
  54408. _this._createHighlightsPostProcess(ratio);
  54409. _this._createDepthOfFieldPostProcess(ratio / 4);
  54410. // Set up pipeline
  54411. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  54412. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  54413. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  54414. if (_this._highlightsGain === -1) {
  54415. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  54416. }
  54417. // Finish
  54418. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54419. if (cameras) {
  54420. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54421. }
  54422. return _this;
  54423. }
  54424. // public methods (self explanatory)
  54425. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  54426. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  54427. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  54428. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  54429. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  54430. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  54431. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  54432. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  54433. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  54434. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  54435. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  54436. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  54437. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  54438. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  54439. };
  54440. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  54441. this._highlightsPostProcess.updateEffect();
  54442. };
  54443. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  54444. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  54445. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  54446. this._highlightsGain = amount;
  54447. };
  54448. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  54449. if (this._highlightsGain === -1) {
  54450. this._highlightsGain = 1.0;
  54451. }
  54452. this._highlightsThreshold = amount;
  54453. };
  54454. LensRenderingPipeline.prototype.disableHighlights = function () {
  54455. this._highlightsGain = -1;
  54456. };
  54457. /**
  54458. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  54459. */
  54460. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  54461. if (disableDepthRender === void 0) { disableDepthRender = false; }
  54462. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54463. this._chromaticAberrationPostProcess = undefined;
  54464. this._highlightsPostProcess = undefined;
  54465. this._depthOfFieldPostProcess = undefined;
  54466. this._grainTexture.dispose();
  54467. if (disableDepthRender)
  54468. this._scene.disableDepthRenderer();
  54469. };
  54470. // colors shifting and distortion
  54471. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  54472. var _this = this;
  54473. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  54474. [], // samplers
  54475. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54476. this._chromaticAberrationPostProcess.onApply = function (effect) {
  54477. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  54478. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54479. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54480. };
  54481. };
  54482. // highlights enhancing
  54483. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  54484. var _this = this;
  54485. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  54486. [], // samplers
  54487. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  54488. this._highlightsPostProcess.onApply = function (effect) {
  54489. effect.setFloat('gain', _this._highlightsGain);
  54490. effect.setFloat('threshold', _this._highlightsThreshold);
  54491. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  54492. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54493. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54494. };
  54495. };
  54496. // colors shifting and distortion
  54497. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  54498. var _this = this;
  54499. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  54500. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  54501. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  54502. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54503. this._depthOfFieldPostProcess.onApply = function (effect) {
  54504. effect.setTexture("depthSampler", _this._depthTexture);
  54505. effect.setTexture("grainSampler", _this._grainTexture);
  54506. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  54507. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  54508. effect.setFloat('grain_amount', _this._grainAmount);
  54509. effect.setBool('blur_noise', _this._blurNoise);
  54510. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54511. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54512. effect.setFloat('distortion', _this._distortion);
  54513. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  54514. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  54515. effect.setFloat('aperture', _this._dofAperture);
  54516. effect.setFloat('darken', _this._dofDarken);
  54517. effect.setFloat('edge_blur', _this._edgeBlur);
  54518. effect.setBool('highlights', (_this._highlightsGain !== -1));
  54519. effect.setFloat('near', _this._scene.activeCamera.minZ);
  54520. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  54521. };
  54522. };
  54523. // creates a black and white random noise texture, 512x512
  54524. LensRenderingPipeline.prototype._createGrainTexture = function () {
  54525. var size = 512;
  54526. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54527. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54528. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54529. var context = this._grainTexture.getContext();
  54530. var rand = function (min, max) {
  54531. return Math.random() * (max - min) + min;
  54532. };
  54533. var value;
  54534. for (var x = 0; x < size; x++) {
  54535. for (var y = 0; y < size; y++) {
  54536. value = Math.floor(rand(0.42, 0.58) * 255);
  54537. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  54538. context.fillRect(x, y, 1, 1);
  54539. }
  54540. }
  54541. this._grainTexture.update(false);
  54542. };
  54543. return LensRenderingPipeline;
  54544. }(BABYLON.PostProcessRenderPipeline));
  54545. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  54546. })(BABYLON || (BABYLON = {}));
  54547. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  54548. var BABYLON;
  54549. (function (BABYLON) {
  54550. var StandardRenderingPipeline = (function (_super) {
  54551. __extends(StandardRenderingPipeline, _super);
  54552. /**
  54553. * @constructor
  54554. * @param {string} name - The rendering pipeline name
  54555. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54556. * @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)
  54557. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54558. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54559. */
  54560. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54561. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54562. var _this = _super.call(this, scene.getEngine(), name) || this;
  54563. _this.downSampleX4PostProcess = null;
  54564. _this.brightPassPostProcess = null;
  54565. _this.blurHPostProcesses = [];
  54566. _this.blurVPostProcesses = [];
  54567. _this.textureAdderPostProcess = null;
  54568. _this.volumetricLightPostProcess = null;
  54569. _this.volumetricLightSmoothXPostProcess = null;
  54570. _this.volumetricLightSmoothYPostProcess = null;
  54571. _this.volumetricLightMergePostProces = null;
  54572. _this.volumetricLightFinalPostProcess = null;
  54573. _this.luminancePostProcess = null;
  54574. _this.luminanceDownSamplePostProcesses = [];
  54575. _this.hdrPostProcess = null;
  54576. _this.textureAdderFinalPostProcess = null;
  54577. _this.lensFlareFinalPostProcess = null;
  54578. _this.hdrFinalPostProcess = null;
  54579. _this.lensFlarePostProcess = null;
  54580. _this.lensFlareComposePostProcess = null;
  54581. _this.motionBlurPostProcess = null;
  54582. _this.depthOfFieldPostProcess = null;
  54583. // Values
  54584. _this.brightThreshold = 1.0;
  54585. _this.blurWidth = 512.0;
  54586. _this.horizontalBlur = false;
  54587. _this.exposure = 1.0;
  54588. _this.lensTexture = null;
  54589. _this.volumetricLightCoefficient = 0.2;
  54590. _this.volumetricLightPower = 4.0;
  54591. _this.volumetricLightBlurScale = 64.0;
  54592. _this.sourceLight = null;
  54593. _this.hdrMinimumLuminance = 1.0;
  54594. _this.hdrDecreaseRate = 0.5;
  54595. _this.hdrIncreaseRate = 0.5;
  54596. _this.lensColorTexture = null;
  54597. _this.lensFlareStrength = 20.0;
  54598. _this.lensFlareGhostDispersal = 1.4;
  54599. _this.lensFlareHaloWidth = 0.7;
  54600. _this.lensFlareDistortionStrength = 16.0;
  54601. _this.lensStarTexture = null;
  54602. _this.lensFlareDirtTexture = null;
  54603. _this.depthOfFieldDistance = 10.0;
  54604. _this.depthOfFieldBlurWidth = 64.0;
  54605. _this.motionStrength = 1.0;
  54606. // IAnimatable
  54607. _this.animations = [];
  54608. _this._currentDepthOfFieldSource = null;
  54609. _this._hdrCurrentLuminance = 1.0;
  54610. // Getters and setters
  54611. _this._bloomEnabled = true;
  54612. _this._depthOfFieldEnabled = false;
  54613. _this._vlsEnabled = false;
  54614. _this._lensFlareEnabled = false;
  54615. _this._hdrEnabled = false;
  54616. _this._motionBlurEnabled = false;
  54617. _this._motionBlurSamples = 64.0;
  54618. _this._volumetricLightStepsCount = 50.0;
  54619. _this._cameras = cameras || [];
  54620. // Initialize
  54621. _this._scene = scene;
  54622. _this._basePostProcess = originalPostProcess;
  54623. _this._ratio = ratio;
  54624. // Misc
  54625. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54626. // Finish
  54627. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54628. _this._buildPipeline();
  54629. return _this;
  54630. }
  54631. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  54632. get: function () {
  54633. return this._bloomEnabled;
  54634. },
  54635. set: function (enabled) {
  54636. if (this._bloomEnabled === enabled) {
  54637. return;
  54638. }
  54639. this._bloomEnabled = enabled;
  54640. this._buildPipeline();
  54641. },
  54642. enumerable: true,
  54643. configurable: true
  54644. });
  54645. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  54646. get: function () {
  54647. return this._depthOfFieldEnabled;
  54648. },
  54649. set: function (enabled) {
  54650. if (this._depthOfFieldEnabled === enabled) {
  54651. return;
  54652. }
  54653. this._depthOfFieldEnabled = enabled;
  54654. this._buildPipeline();
  54655. },
  54656. enumerable: true,
  54657. configurable: true
  54658. });
  54659. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  54660. get: function () {
  54661. return this._lensFlareEnabled;
  54662. },
  54663. set: function (enabled) {
  54664. if (this._lensFlareEnabled === enabled) {
  54665. return;
  54666. }
  54667. this._lensFlareEnabled = enabled;
  54668. this._buildPipeline();
  54669. },
  54670. enumerable: true,
  54671. configurable: true
  54672. });
  54673. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  54674. get: function () {
  54675. return this._hdrEnabled;
  54676. },
  54677. set: function (enabled) {
  54678. if (this._hdrEnabled === enabled) {
  54679. return;
  54680. }
  54681. this._hdrEnabled = enabled;
  54682. this._buildPipeline();
  54683. },
  54684. enumerable: true,
  54685. configurable: true
  54686. });
  54687. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  54688. get: function () {
  54689. return this._vlsEnabled;
  54690. },
  54691. set: function (enabled) {
  54692. if (this._vlsEnabled === enabled) {
  54693. return;
  54694. }
  54695. if (enabled) {
  54696. var geometry = this._scene.enableGeometryBufferRenderer();
  54697. if (!geometry) {
  54698. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  54699. return;
  54700. }
  54701. }
  54702. this._vlsEnabled = enabled;
  54703. this._buildPipeline();
  54704. },
  54705. enumerable: true,
  54706. configurable: true
  54707. });
  54708. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  54709. get: function () {
  54710. return this._motionBlurEnabled;
  54711. },
  54712. set: function (enabled) {
  54713. if (this._motionBlurEnabled === enabled) {
  54714. return;
  54715. }
  54716. this._motionBlurEnabled = enabled;
  54717. this._buildPipeline();
  54718. },
  54719. enumerable: true,
  54720. configurable: true
  54721. });
  54722. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  54723. get: function () {
  54724. return this._volumetricLightStepsCount;
  54725. },
  54726. set: function (count) {
  54727. if (this.volumetricLightPostProcess) {
  54728. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  54729. }
  54730. this._volumetricLightStepsCount = count;
  54731. },
  54732. enumerable: true,
  54733. configurable: true
  54734. });
  54735. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  54736. get: function () {
  54737. return this._motionBlurSamples;
  54738. },
  54739. set: function (samples) {
  54740. if (this.motionBlurPostProcess) {
  54741. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  54742. }
  54743. this._motionBlurSamples = samples;
  54744. },
  54745. enumerable: true,
  54746. configurable: true
  54747. });
  54748. StandardRenderingPipeline.prototype._buildPipeline = function () {
  54749. var _this = this;
  54750. var ratio = this._ratio;
  54751. var scene = this._scene;
  54752. this._disposePostProcesses();
  54753. this._reset();
  54754. // Create pass post-process
  54755. if (!this._basePostProcess) {
  54756. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  54757. this.originalPostProcess.onApply = function (effect) {
  54758. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  54759. };
  54760. }
  54761. else {
  54762. this.originalPostProcess = this._basePostProcess;
  54763. }
  54764. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  54765. this._currentDepthOfFieldSource = this.originalPostProcess;
  54766. if (this._vlsEnabled) {
  54767. // Create volumetric light
  54768. this._createVolumetricLightPostProcess(scene, ratio);
  54769. // Create volumetric light final post-process
  54770. 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);
  54771. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  54772. }
  54773. if (this._bloomEnabled) {
  54774. // Create down sample X4 post-process
  54775. this._createDownSampleX4PostProcess(scene, ratio / 2);
  54776. // Create bright pass post-process
  54777. this._createBrightPassPostProcess(scene, ratio / 2);
  54778. // Create gaussian blur post-processes (down sampling blurs)
  54779. this._createBlurPostProcesses(scene, ratio / 4, 1);
  54780. // Create texture adder post-process
  54781. this._createTextureAdderPostProcess(scene, ratio);
  54782. // Create depth-of-field source post-process
  54783. 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);
  54784. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  54785. }
  54786. if (this._lensFlareEnabled) {
  54787. // Create lens flare post-process
  54788. this._createLensFlarePostProcess(scene, ratio);
  54789. // Create depth-of-field source post-process post lens-flare and disable it now
  54790. 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);
  54791. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  54792. }
  54793. if (this._hdrEnabled) {
  54794. // Create luminance
  54795. this._createLuminancePostProcesses(scene, this._floatTextureType);
  54796. // Create HDR
  54797. this._createHdrPostProcess(scene, ratio);
  54798. // Create depth-of-field source post-process post hdr and disable it now
  54799. 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);
  54800. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  54801. }
  54802. if (this._depthOfFieldEnabled) {
  54803. // Create gaussian blur used by depth-of-field
  54804. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  54805. // Create depth-of-field post-process
  54806. this._createDepthOfFieldPostProcess(scene, ratio);
  54807. }
  54808. if (this._motionBlurEnabled) {
  54809. // Create motion blur post-process
  54810. this._createMotionBlurPostProcess(scene, ratio);
  54811. }
  54812. if (this._cameras !== null) {
  54813. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  54814. }
  54815. };
  54816. // Down Sample X4 Post-Processs
  54817. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54818. var _this = this;
  54819. var downSampleX4Offsets = new Array(32);
  54820. 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);
  54821. this.downSampleX4PostProcess.onApply = function (effect) {
  54822. var id = 0;
  54823. for (var i = -2; i < 2; i++) {
  54824. for (var j = -2; j < 2; j++) {
  54825. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  54826. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  54827. id += 2;
  54828. }
  54829. }
  54830. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54831. };
  54832. // Add to pipeline
  54833. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  54834. };
  54835. // Brightpass Post-Process
  54836. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54837. var _this = this;
  54838. var brightOffsets = new Array(8);
  54839. 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);
  54840. this.brightPassPostProcess.onApply = function (effect) {
  54841. var sU = (1.0 / _this.brightPassPostProcess.width);
  54842. var sV = (1.0 / _this.brightPassPostProcess.height);
  54843. brightOffsets[0] = -0.5 * sU;
  54844. brightOffsets[1] = 0.5 * sV;
  54845. brightOffsets[2] = 0.5 * sU;
  54846. brightOffsets[3] = 0.5 * sV;
  54847. brightOffsets[4] = -0.5 * sU;
  54848. brightOffsets[5] = -0.5 * sV;
  54849. brightOffsets[6] = 0.5 * sU;
  54850. brightOffsets[7] = -0.5 * sV;
  54851. effect.setArray2("dsOffsets", brightOffsets);
  54852. effect.setFloat("brightThreshold", _this.brightThreshold);
  54853. };
  54854. // Add to pipeline
  54855. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  54856. };
  54857. // Create blur H&V post-processes
  54858. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  54859. var _this = this;
  54860. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  54861. var engine = scene.getEngine();
  54862. 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);
  54863. 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);
  54864. blurX.onActivateObservable.add(function () {
  54865. var dw = blurX.width / engine.getRenderingCanvas().width;
  54866. blurX.kernel = _this[blurWidthKey] * dw;
  54867. });
  54868. blurY.onActivateObservable.add(function () {
  54869. var dw = blurY.height / engine.getRenderingCanvas().height;
  54870. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  54871. });
  54872. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  54873. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  54874. this.blurHPostProcesses.push(blurX);
  54875. this.blurVPostProcesses.push(blurY);
  54876. };
  54877. // Create texture adder post-process
  54878. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54879. var _this = this;
  54880. 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);
  54881. this.textureAdderPostProcess.onApply = function (effect) {
  54882. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  54883. effect.setTexture("lensSampler", _this.lensTexture);
  54884. effect.setFloat("exposure", _this.exposure);
  54885. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  54886. };
  54887. // Add to pipeline
  54888. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  54889. };
  54890. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  54891. var _this = this;
  54892. var geometryRenderer = scene.enableGeometryBufferRenderer();
  54893. geometryRenderer.enablePosition = true;
  54894. var geometry = geometryRenderer.getGBuffer();
  54895. // Base post-process
  54896. 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));
  54897. var depthValues = BABYLON.Vector2.Zero();
  54898. this.volumetricLightPostProcess.onApply = function (effect) {
  54899. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  54900. var generator = _this.sourceLight.getShadowGenerator();
  54901. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  54902. effect.setTexture("positionSampler", geometry.textures[2]);
  54903. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  54904. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  54905. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  54906. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  54907. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  54908. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  54909. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  54910. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  54911. effect.setVector2("depthValues", depthValues);
  54912. }
  54913. };
  54914. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  54915. // Smooth
  54916. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  54917. // Merge
  54918. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  54919. this.volumetricLightMergePostProces.onApply = function (effect) {
  54920. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  54921. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  54922. };
  54923. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  54924. };
  54925. // Create luminance
  54926. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  54927. var _this = this;
  54928. // Create luminance
  54929. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  54930. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  54931. var offsets = [];
  54932. this.luminancePostProcess.onApply = function (effect) {
  54933. var sU = (1.0 / _this.luminancePostProcess.width);
  54934. var sV = (1.0 / _this.luminancePostProcess.height);
  54935. offsets[0] = -0.5 * sU;
  54936. offsets[1] = 0.5 * sV;
  54937. offsets[2] = 0.5 * sU;
  54938. offsets[3] = 0.5 * sV;
  54939. offsets[4] = -0.5 * sU;
  54940. offsets[5] = -0.5 * sV;
  54941. offsets[6] = 0.5 * sU;
  54942. offsets[7] = -0.5 * sV;
  54943. effect.setArray2("lumOffsets", offsets);
  54944. };
  54945. // Add to pipeline
  54946. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  54947. // Create down sample luminance
  54948. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  54949. var size = Math.pow(3, i);
  54950. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  54951. if (i === 0) {
  54952. defines += "#define FINAL_DOWN_SAMPLER";
  54953. }
  54954. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  54955. this.luminanceDownSamplePostProcesses.push(postProcess);
  54956. }
  54957. // Create callbacks and add effects
  54958. var lastLuminance = this.luminancePostProcess;
  54959. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  54960. var downSampleOffsets = new Array(18);
  54961. pp.onApply = function (effect) {
  54962. var id = 0;
  54963. for (var x = -1; x < 2; x++) {
  54964. for (var y = -1; y < 2; y++) {
  54965. downSampleOffsets[id] = x / lastLuminance.width;
  54966. downSampleOffsets[id + 1] = y / lastLuminance.height;
  54967. id += 2;
  54968. }
  54969. }
  54970. effect.setArray2("dsOffsets", downSampleOffsets);
  54971. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  54972. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  54973. lastLuminance = _this.luminancePostProcess;
  54974. }
  54975. else {
  54976. lastLuminance = pp;
  54977. }
  54978. };
  54979. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  54980. pp.onAfterRender = function (effect) {
  54981. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  54982. 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);
  54983. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  54984. };
  54985. }
  54986. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  54987. });
  54988. };
  54989. // Create HDR post-process
  54990. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  54991. var _this = this;
  54992. 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);
  54993. var outputLiminance = 1;
  54994. var time = 0;
  54995. var lastTime = 0;
  54996. this.hdrPostProcess.onApply = function (effect) {
  54997. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  54998. time += scene.getEngine().getDeltaTime();
  54999. if (outputLiminance < 0) {
  55000. outputLiminance = _this._hdrCurrentLuminance;
  55001. }
  55002. else {
  55003. var dt = (lastTime - time) / 1000.0;
  55004. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  55005. outputLiminance += _this.hdrDecreaseRate * dt;
  55006. }
  55007. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  55008. outputLiminance -= _this.hdrIncreaseRate * dt;
  55009. }
  55010. else {
  55011. outputLiminance = _this._hdrCurrentLuminance;
  55012. }
  55013. }
  55014. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  55015. effect.setFloat("averageLuminance", outputLiminance);
  55016. lastTime = time;
  55017. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  55018. };
  55019. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  55020. };
  55021. // Create lens flare post-process
  55022. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  55023. var _this = this;
  55024. 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);
  55025. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  55026. this._createBlurPostProcesses(scene, ratio / 4, 2);
  55027. 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);
  55028. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  55029. var resolution = new BABYLON.Vector2(0, 0);
  55030. // Lens flare
  55031. this.lensFlarePostProcess.onApply = function (effect) {
  55032. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  55033. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  55034. effect.setFloat("strength", _this.lensFlareStrength);
  55035. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  55036. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  55037. // Shift
  55038. resolution.x = _this.lensFlarePostProcess.width;
  55039. resolution.y = _this.lensFlarePostProcess.height;
  55040. effect.setVector2("resolution", resolution);
  55041. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  55042. };
  55043. // Compose
  55044. 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);
  55045. 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);
  55046. this.lensFlareComposePostProcess.onApply = function (effect) {
  55047. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  55048. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  55049. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  55050. // Lens start rotation matrix
  55051. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  55052. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  55053. 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));
  55054. camRot *= 4.0;
  55055. 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);
  55056. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  55057. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  55058. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  55059. };
  55060. };
  55061. // Create depth-of-field post-process
  55062. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  55063. var _this = this;
  55064. 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);
  55065. this.depthOfFieldPostProcess.onApply = function (effect) {
  55066. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  55067. effect.setTexture("depthSampler", _this._getDepthTexture());
  55068. effect.setFloat("distance", _this.depthOfFieldDistance);
  55069. };
  55070. // Add to pipeline
  55071. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  55072. };
  55073. // Create motion blur post-process
  55074. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  55075. var _this = this;
  55076. 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);
  55077. var motionScale = 0;
  55078. var prevViewProjection = BABYLON.Matrix.Identity();
  55079. var invViewProjection = BABYLON.Matrix.Identity();
  55080. var viewProjection = BABYLON.Matrix.Identity();
  55081. var screenSize = BABYLON.Vector2.Zero();
  55082. this.motionBlurPostProcess.onApply = function (effect) {
  55083. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  55084. viewProjection.invertToRef(invViewProjection);
  55085. effect.setMatrix("inverseViewProjection", invViewProjection);
  55086. effect.setMatrix("prevViewProjection", prevViewProjection);
  55087. prevViewProjection = viewProjection;
  55088. screenSize.x = _this.motionBlurPostProcess.width;
  55089. screenSize.y = _this.motionBlurPostProcess.height;
  55090. effect.setVector2("screenSize", screenSize);
  55091. motionScale = scene.getEngine().getFps() / 60.0;
  55092. effect.setFloat("motionScale", motionScale);
  55093. effect.setFloat("motionStrength", _this.motionStrength);
  55094. effect.setTexture("depthSampler", _this._getDepthTexture());
  55095. };
  55096. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  55097. };
  55098. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  55099. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  55100. return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  55101. }
  55102. return this._scene.enableDepthRenderer().getDepthMap();
  55103. };
  55104. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  55105. for (var i = 0; i < this._cameras.length; i++) {
  55106. var camera = this._cameras[i];
  55107. if (this.originalPostProcess) {
  55108. this.originalPostProcess.dispose(camera);
  55109. }
  55110. if (this.downSampleX4PostProcess) {
  55111. this.downSampleX4PostProcess.dispose(camera);
  55112. }
  55113. if (this.brightPassPostProcess) {
  55114. this.brightPassPostProcess.dispose(camera);
  55115. }
  55116. if (this.textureAdderPostProcess) {
  55117. this.textureAdderPostProcess.dispose(camera);
  55118. }
  55119. if (this.textureAdderFinalPostProcess) {
  55120. this.textureAdderFinalPostProcess.dispose(camera);
  55121. }
  55122. if (this.volumetricLightPostProcess) {
  55123. this.volumetricLightPostProcess.dispose(camera);
  55124. }
  55125. if (this.volumetricLightSmoothXPostProcess) {
  55126. this.volumetricLightSmoothXPostProcess.dispose(camera);
  55127. }
  55128. if (this.volumetricLightSmoothYPostProcess) {
  55129. this.volumetricLightSmoothYPostProcess.dispose(camera);
  55130. }
  55131. if (this.volumetricLightMergePostProces) {
  55132. this.volumetricLightMergePostProces.dispose(camera);
  55133. }
  55134. if (this.volumetricLightFinalPostProcess) {
  55135. this.volumetricLightFinalPostProcess.dispose(camera);
  55136. }
  55137. if (this.lensFlarePostProcess) {
  55138. this.lensFlarePostProcess.dispose(camera);
  55139. }
  55140. if (this.lensFlareComposePostProcess) {
  55141. this.lensFlareComposePostProcess.dispose(camera);
  55142. }
  55143. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  55144. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  55145. }
  55146. if (this.luminancePostProcess) {
  55147. this.luminancePostProcess.dispose(camera);
  55148. }
  55149. if (this.hdrPostProcess) {
  55150. this.hdrPostProcess.dispose(camera);
  55151. }
  55152. if (this.hdrFinalPostProcess) {
  55153. this.hdrFinalPostProcess.dispose(camera);
  55154. }
  55155. if (this.depthOfFieldPostProcess) {
  55156. this.depthOfFieldPostProcess.dispose(camera);
  55157. }
  55158. if (this.motionBlurPostProcess) {
  55159. this.motionBlurPostProcess.dispose(camera);
  55160. }
  55161. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  55162. this.blurHPostProcesses[j].dispose(camera);
  55163. }
  55164. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  55165. this.blurVPostProcesses[j].dispose(camera);
  55166. }
  55167. }
  55168. this.originalPostProcess = null;
  55169. this.downSampleX4PostProcess = null;
  55170. this.brightPassPostProcess = null;
  55171. this.textureAdderPostProcess = null;
  55172. this.textureAdderFinalPostProcess = null;
  55173. this.volumetricLightPostProcess = null;
  55174. this.volumetricLightSmoothXPostProcess = null;
  55175. this.volumetricLightSmoothYPostProcess = null;
  55176. this.volumetricLightMergePostProces = null;
  55177. this.volumetricLightFinalPostProcess = null;
  55178. this.lensFlarePostProcess = null;
  55179. this.lensFlareComposePostProcess = null;
  55180. this.luminancePostProcess = null;
  55181. this.hdrPostProcess = null;
  55182. this.hdrFinalPostProcess = null;
  55183. this.depthOfFieldPostProcess = null;
  55184. this.motionBlurPostProcess = null;
  55185. this.luminanceDownSamplePostProcesses = [];
  55186. this.blurHPostProcesses = [];
  55187. this.blurVPostProcesses = [];
  55188. };
  55189. // Dispose
  55190. StandardRenderingPipeline.prototype.dispose = function () {
  55191. this._disposePostProcesses();
  55192. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  55193. _super.prototype.dispose.call(this);
  55194. };
  55195. // Serialize rendering pipeline
  55196. StandardRenderingPipeline.prototype.serialize = function () {
  55197. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55198. serializationObject.customType = "StandardRenderingPipeline";
  55199. return serializationObject;
  55200. };
  55201. /**
  55202. * Static members
  55203. */
  55204. // Parse serialized pipeline
  55205. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  55206. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  55207. };
  55208. return StandardRenderingPipeline;
  55209. }(BABYLON.PostProcessRenderPipeline));
  55210. // Luminance steps
  55211. StandardRenderingPipeline.LuminanceSteps = 6;
  55212. __decorate([
  55213. BABYLON.serialize()
  55214. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  55215. __decorate([
  55216. BABYLON.serialize()
  55217. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  55218. __decorate([
  55219. BABYLON.serialize()
  55220. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  55221. __decorate([
  55222. BABYLON.serialize()
  55223. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  55224. __decorate([
  55225. BABYLON.serializeAsTexture("lensTexture")
  55226. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  55227. __decorate([
  55228. BABYLON.serialize()
  55229. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  55230. __decorate([
  55231. BABYLON.serialize()
  55232. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  55233. __decorate([
  55234. BABYLON.serialize()
  55235. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  55236. __decorate([
  55237. BABYLON.serialize()
  55238. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  55239. __decorate([
  55240. BABYLON.serialize()
  55241. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  55242. __decorate([
  55243. BABYLON.serialize()
  55244. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  55245. __decorate([
  55246. BABYLON.serializeAsTexture("lensColorTexture")
  55247. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  55248. __decorate([
  55249. BABYLON.serialize()
  55250. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  55251. __decorate([
  55252. BABYLON.serialize()
  55253. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  55254. __decorate([
  55255. BABYLON.serialize()
  55256. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  55257. __decorate([
  55258. BABYLON.serialize()
  55259. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  55260. __decorate([
  55261. BABYLON.serializeAsTexture("lensStarTexture")
  55262. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  55263. __decorate([
  55264. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  55265. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  55266. __decorate([
  55267. BABYLON.serialize()
  55268. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  55269. __decorate([
  55270. BABYLON.serialize()
  55271. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  55272. __decorate([
  55273. BABYLON.serialize()
  55274. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  55275. __decorate([
  55276. BABYLON.serialize()
  55277. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  55278. __decorate([
  55279. BABYLON.serialize()
  55280. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  55281. __decorate([
  55282. BABYLON.serialize()
  55283. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  55284. __decorate([
  55285. BABYLON.serialize()
  55286. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  55287. __decorate([
  55288. BABYLON.serialize()
  55289. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  55290. __decorate([
  55291. BABYLON.serialize()
  55292. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  55293. __decorate([
  55294. BABYLON.serialize()
  55295. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  55296. __decorate([
  55297. BABYLON.serialize()
  55298. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  55299. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  55300. })(BABYLON || (BABYLON = {}));
  55301. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  55302. var BABYLON;
  55303. (function (BABYLON) {
  55304. var FxaaPostProcess = (function (_super) {
  55305. __extends(FxaaPostProcess, _super);
  55306. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55307. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55308. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  55309. _this.onApplyObservable.add(function (effect) {
  55310. var texelSize = _this.texelSize;
  55311. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  55312. });
  55313. return _this;
  55314. }
  55315. return FxaaPostProcess;
  55316. }(BABYLON.PostProcess));
  55317. BABYLON.FxaaPostProcess = FxaaPostProcess;
  55318. })(BABYLON || (BABYLON = {}));
  55319. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  55320. var BABYLON;
  55321. (function (BABYLON) {
  55322. var DefaultRenderingPipeline = (function (_super) {
  55323. __extends(DefaultRenderingPipeline, _super);
  55324. /**
  55325. * @constructor
  55326. * @param {string} name - The rendering pipeline name
  55327. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55328. * @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)
  55329. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55330. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  55331. */
  55332. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  55333. if (automaticBuild === void 0) { automaticBuild = true; }
  55334. var _this = _super.call(this, scene.getEngine(), name) || this;
  55335. _this.PassPostProcessId = "PassPostProcessEffect";
  55336. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  55337. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  55338. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  55339. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  55340. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  55341. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  55342. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  55343. // IAnimatable
  55344. _this.animations = [];
  55345. // Values
  55346. _this._bloomEnabled = false;
  55347. _this._fxaaEnabled = false;
  55348. _this._imageProcessingEnabled = true;
  55349. _this._bloomScale = 0.6;
  55350. _this._buildAllowed = true;
  55351. /**
  55352. * Specifies the size of the bloom blur kernel, relative to the final output size
  55353. */
  55354. _this.bloomKernel = 64;
  55355. /**
  55356. * Specifies the weight of the bloom in the final rendering
  55357. */
  55358. _this._bloomWeight = 0.15;
  55359. _this._cameras = cameras || [];
  55360. _this._buildAllowed = automaticBuild;
  55361. // Initialize
  55362. _this._scene = scene;
  55363. var caps = _this._scene.getEngine().getCaps();
  55364. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  55365. // Misc
  55366. if (_this._hdr) {
  55367. if (caps.textureHalfFloatRender) {
  55368. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55369. }
  55370. else if (caps.textureFloatRender) {
  55371. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55372. }
  55373. }
  55374. else {
  55375. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55376. }
  55377. // Attach
  55378. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55379. _this._buildPipeline();
  55380. return _this;
  55381. }
  55382. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  55383. get: function () {
  55384. return this._bloomWeight;
  55385. },
  55386. set: function (value) {
  55387. if (this._bloomWeight === value) {
  55388. return;
  55389. }
  55390. this._bloomWeight = value;
  55391. if (this._hdr && this.copyBack) {
  55392. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  55393. }
  55394. },
  55395. enumerable: true,
  55396. configurable: true
  55397. });
  55398. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  55399. get: function () {
  55400. return this._bloomScale;
  55401. },
  55402. set: function (value) {
  55403. if (this._bloomScale === value) {
  55404. return;
  55405. }
  55406. this._bloomScale = value;
  55407. this._buildPipeline();
  55408. },
  55409. enumerable: true,
  55410. configurable: true
  55411. });
  55412. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  55413. get: function () {
  55414. return this._bloomEnabled;
  55415. },
  55416. set: function (enabled) {
  55417. if (this._bloomEnabled === enabled) {
  55418. return;
  55419. }
  55420. this._bloomEnabled = enabled;
  55421. this._buildPipeline();
  55422. },
  55423. enumerable: true,
  55424. configurable: true
  55425. });
  55426. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  55427. get: function () {
  55428. return this._fxaaEnabled;
  55429. },
  55430. set: function (enabled) {
  55431. if (this._fxaaEnabled === enabled) {
  55432. return;
  55433. }
  55434. this._fxaaEnabled = enabled;
  55435. this._buildPipeline();
  55436. },
  55437. enumerable: true,
  55438. configurable: true
  55439. });
  55440. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  55441. get: function () {
  55442. return this._imageProcessingEnabled;
  55443. },
  55444. set: function (enabled) {
  55445. if (this._imageProcessingEnabled === enabled) {
  55446. return;
  55447. }
  55448. this._imageProcessingEnabled = enabled;
  55449. this._buildPipeline();
  55450. },
  55451. enumerable: true,
  55452. configurable: true
  55453. });
  55454. /**
  55455. * Force the compilation of the entire pipeline.
  55456. */
  55457. DefaultRenderingPipeline.prototype.prepare = function () {
  55458. var previousState = this._buildAllowed;
  55459. this._buildAllowed = true;
  55460. this._buildPipeline();
  55461. this._buildAllowed = previousState;
  55462. };
  55463. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  55464. var _this = this;
  55465. if (!this._buildAllowed) {
  55466. return;
  55467. }
  55468. var engine = this._scene.getEngine();
  55469. this._disposePostProcesses();
  55470. this._reset();
  55471. if (this.bloomEnabled) {
  55472. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55473. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  55474. if (!this._hdr) {
  55475. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55476. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  55477. this.highlights.autoClear = false;
  55478. this.highlights.alwaysForcePOT = true;
  55479. }
  55480. 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);
  55481. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  55482. this.blurX.alwaysForcePOT = true;
  55483. this.blurX.autoClear = false;
  55484. this.blurX.onActivateObservable.add(function () {
  55485. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  55486. _this.blurX.kernel = _this.bloomKernel * dw;
  55487. });
  55488. 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);
  55489. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  55490. this.blurY.alwaysForcePOT = true;
  55491. this.blurY.autoClear = false;
  55492. this.blurY.onActivateObservable.add(function () {
  55493. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  55494. _this.blurY.kernel = _this.bloomKernel * dh;
  55495. });
  55496. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55497. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  55498. this.copyBack.alwaysForcePOT = true;
  55499. if (this._hdr) {
  55500. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  55501. var w = this.bloomWeight;
  55502. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  55503. }
  55504. else {
  55505. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  55506. }
  55507. this.copyBack.autoClear = false;
  55508. }
  55509. if (this._imageProcessingEnabled) {
  55510. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55511. if (this._hdr) {
  55512. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  55513. }
  55514. else {
  55515. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  55516. }
  55517. }
  55518. if (this.fxaaEnabled) {
  55519. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55520. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  55521. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  55522. }
  55523. else {
  55524. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55525. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  55526. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  55527. }
  55528. if (this.bloomEnabled) {
  55529. if (this._hdr) {
  55530. this.copyBack.shareOutputWith(this.blurX);
  55531. if (this.imageProcessing) {
  55532. this.imageProcessing.shareOutputWith(this.pass);
  55533. this.imageProcessing.autoClear = false;
  55534. }
  55535. else if (this.fxaa) {
  55536. this.fxaa.shareOutputWith(this.pass);
  55537. }
  55538. else {
  55539. this.finalMerge.shareOutputWith(this.pass);
  55540. }
  55541. }
  55542. else {
  55543. if (this.fxaa) {
  55544. this.fxaa.shareOutputWith(this.pass);
  55545. }
  55546. else {
  55547. this.finalMerge.shareOutputWith(this.pass);
  55548. }
  55549. }
  55550. }
  55551. if (this._cameras !== null) {
  55552. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  55553. }
  55554. };
  55555. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  55556. for (var i = 0; i < this._cameras.length; i++) {
  55557. var camera = this._cameras[i];
  55558. if (this.pass) {
  55559. this.pass.dispose(camera);
  55560. }
  55561. if (this.highlights) {
  55562. this.highlights.dispose(camera);
  55563. }
  55564. if (this.blurX) {
  55565. this.blurX.dispose(camera);
  55566. }
  55567. if (this.blurY) {
  55568. this.blurY.dispose(camera);
  55569. }
  55570. if (this.copyBack) {
  55571. this.copyBack.dispose(camera);
  55572. }
  55573. if (this.imageProcessing) {
  55574. this.imageProcessing.dispose(camera);
  55575. }
  55576. if (this.fxaa) {
  55577. this.fxaa.dispose(camera);
  55578. }
  55579. if (this.finalMerge) {
  55580. this.finalMerge.dispose(camera);
  55581. }
  55582. }
  55583. this.pass = null;
  55584. this.highlights = null;
  55585. this.blurX = null;
  55586. this.blurY = null;
  55587. this.copyBack = null;
  55588. this.imageProcessing = null;
  55589. this.fxaa = null;
  55590. this.finalMerge = null;
  55591. };
  55592. // Dispose
  55593. DefaultRenderingPipeline.prototype.dispose = function () {
  55594. this._disposePostProcesses();
  55595. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  55596. _super.prototype.dispose.call(this);
  55597. };
  55598. // Serialize rendering pipeline
  55599. DefaultRenderingPipeline.prototype.serialize = function () {
  55600. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55601. serializationObject.customType = "DefaultRenderingPipeline";
  55602. return serializationObject;
  55603. };
  55604. // Parse serialized pipeline
  55605. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  55606. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  55607. };
  55608. return DefaultRenderingPipeline;
  55609. }(BABYLON.PostProcessRenderPipeline));
  55610. __decorate([
  55611. BABYLON.serialize()
  55612. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  55613. __decorate([
  55614. BABYLON.serialize()
  55615. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  55616. __decorate([
  55617. BABYLON.serialize()
  55618. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  55619. __decorate([
  55620. BABYLON.serialize()
  55621. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  55622. __decorate([
  55623. BABYLON.serialize()
  55624. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  55625. __decorate([
  55626. BABYLON.serialize()
  55627. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  55628. __decorate([
  55629. BABYLON.serialize()
  55630. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  55631. __decorate([
  55632. BABYLON.serialize()
  55633. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  55634. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  55635. })(BABYLON || (BABYLON = {}));
  55636. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  55637. var BABYLON;
  55638. (function (BABYLON) {
  55639. var GeometryBufferRenderer = (function () {
  55640. function GeometryBufferRenderer(scene, ratio) {
  55641. if (ratio === void 0) { ratio = 1; }
  55642. this._viewMatrix = BABYLON.Matrix.Zero();
  55643. this._projectionMatrix = BABYLON.Matrix.Zero();
  55644. this._transformMatrix = BABYLON.Matrix.Zero();
  55645. this._worldViewProjection = BABYLON.Matrix.Zero();
  55646. this._enablePosition = false;
  55647. this._scene = scene;
  55648. this._ratio = ratio;
  55649. // Render target
  55650. this._createRenderTargets();
  55651. }
  55652. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  55653. set: function (meshes) {
  55654. this._multiRenderTarget.renderList = meshes;
  55655. },
  55656. enumerable: true,
  55657. configurable: true
  55658. });
  55659. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  55660. get: function () {
  55661. return this._multiRenderTarget.isSupported;
  55662. },
  55663. enumerable: true,
  55664. configurable: true
  55665. });
  55666. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  55667. get: function () {
  55668. return this._enablePosition;
  55669. },
  55670. set: function (enable) {
  55671. this._enablePosition = enable;
  55672. this.dispose();
  55673. this._createRenderTargets();
  55674. },
  55675. enumerable: true,
  55676. configurable: true
  55677. });
  55678. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  55679. var material = subMesh.getMaterial();
  55680. if (material && material.disableDepthWrite) {
  55681. return false;
  55682. }
  55683. var defines = [];
  55684. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  55685. var mesh = subMesh.getMesh();
  55686. var scene = mesh.getScene();
  55687. // Alpha test
  55688. if (material && material.needAlphaTesting()) {
  55689. defines.push("#define ALPHATEST");
  55690. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55691. attribs.push(BABYLON.VertexBuffer.UVKind);
  55692. defines.push("#define UV1");
  55693. }
  55694. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55695. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55696. defines.push("#define UV2");
  55697. }
  55698. }
  55699. // Buffers
  55700. if (this._enablePosition) {
  55701. defines.push("#define POSITION");
  55702. }
  55703. // Bones
  55704. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55705. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55706. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55707. if (mesh.numBoneInfluencers > 4) {
  55708. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55709. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55710. }
  55711. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55712. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55713. }
  55714. else {
  55715. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55716. }
  55717. // Instances
  55718. if (useInstances) {
  55719. defines.push("#define INSTANCES");
  55720. attribs.push("world0");
  55721. attribs.push("world1");
  55722. attribs.push("world2");
  55723. attribs.push("world3");
  55724. }
  55725. // Get correct effect
  55726. var join = defines.join("\n");
  55727. if (this._cachedDefines !== join) {
  55728. this._cachedDefines = join;
  55729. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, null, null, null, { buffersCount: this._enablePosition ? 3 : 2 });
  55730. }
  55731. return this._effect.isReady();
  55732. };
  55733. GeometryBufferRenderer.prototype.getGBuffer = function () {
  55734. return this._multiRenderTarget;
  55735. };
  55736. // Methods
  55737. GeometryBufferRenderer.prototype.dispose = function () {
  55738. this.getGBuffer().dispose();
  55739. };
  55740. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  55741. var _this = this;
  55742. var engine = this._scene.getEngine();
  55743. var count = this._enablePosition ? 3 : 2;
  55744. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  55745. if (!this.isSupported) {
  55746. return null;
  55747. }
  55748. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55749. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55750. this._multiRenderTarget.refreshRate = 1;
  55751. this._multiRenderTarget.renderParticles = false;
  55752. this._multiRenderTarget.renderList = null;
  55753. // set default depth value to 1.0 (far away)
  55754. this._multiRenderTarget.onClearObservable.add(function (engine) {
  55755. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  55756. });
  55757. // Custom render function
  55758. var renderSubMesh = function (subMesh) {
  55759. var mesh = subMesh.getRenderingMesh();
  55760. var scene = _this._scene;
  55761. var engine = scene.getEngine();
  55762. // Culling
  55763. engine.setState(subMesh.getMaterial().backFaceCulling);
  55764. // Managing instances
  55765. var batch = mesh._getInstancesRenderList(subMesh._id);
  55766. if (batch.mustReturn) {
  55767. return;
  55768. }
  55769. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  55770. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55771. engine.enableEffect(_this._effect);
  55772. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  55773. var material = subMesh.getMaterial();
  55774. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  55775. _this._effect.setMatrix("view", scene.getViewMatrix());
  55776. // Alpha test
  55777. if (material && material.needAlphaTesting()) {
  55778. var alphaTexture = material.getAlphaTestTexture();
  55779. _this._effect.setTexture("diffuseSampler", alphaTexture);
  55780. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55781. }
  55782. // Bones
  55783. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55784. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55785. }
  55786. // Draw
  55787. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55788. }
  55789. };
  55790. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55791. var index;
  55792. if (depthOnlySubMeshes.length) {
  55793. engine.setColorWrite(false);
  55794. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55795. renderSubMesh(depthOnlySubMeshes.data[index]);
  55796. }
  55797. engine.setColorWrite(true);
  55798. }
  55799. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55800. renderSubMesh(opaqueSubMeshes.data[index]);
  55801. }
  55802. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55803. renderSubMesh(alphaTestSubMeshes.data[index]);
  55804. }
  55805. };
  55806. };
  55807. return GeometryBufferRenderer;
  55808. }());
  55809. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  55810. })(BABYLON || (BABYLON = {}));
  55811. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  55812. var BABYLON;
  55813. (function (BABYLON) {
  55814. var RefractionPostProcess = (function (_super) {
  55815. __extends(RefractionPostProcess, _super);
  55816. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  55817. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  55818. _this.color = color;
  55819. _this.depth = depth;
  55820. _this.colorLevel = colorLevel;
  55821. _this.onActivateObservable.add(function (cam) {
  55822. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  55823. });
  55824. _this.onApplyObservable.add(function (effect) {
  55825. effect.setColor3("baseColor", _this.color);
  55826. effect.setFloat("depth", _this.depth);
  55827. effect.setFloat("colorLevel", _this.colorLevel);
  55828. effect.setTexture("refractionSampler", _this._refRexture);
  55829. });
  55830. return _this;
  55831. }
  55832. // Methods
  55833. RefractionPostProcess.prototype.dispose = function (camera) {
  55834. if (this._refRexture) {
  55835. this._refRexture.dispose();
  55836. }
  55837. _super.prototype.dispose.call(this, camera);
  55838. };
  55839. return RefractionPostProcess;
  55840. }(BABYLON.PostProcess));
  55841. BABYLON.RefractionPostProcess = RefractionPostProcess;
  55842. })(BABYLON || (BABYLON = {}));
  55843. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  55844. var BABYLON;
  55845. (function (BABYLON) {
  55846. var BlackAndWhitePostProcess = (function (_super) {
  55847. __extends(BlackAndWhitePostProcess, _super);
  55848. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  55849. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  55850. _this.degree = 1;
  55851. _this.onApplyObservable.add(function (effect) {
  55852. effect.setFloat("degree", _this.degree);
  55853. });
  55854. return _this;
  55855. }
  55856. return BlackAndWhitePostProcess;
  55857. }(BABYLON.PostProcess));
  55858. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  55859. })(BABYLON || (BABYLON = {}));
  55860. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  55861. var BABYLON;
  55862. (function (BABYLON) {
  55863. var ConvolutionPostProcess = (function (_super) {
  55864. __extends(ConvolutionPostProcess, _super);
  55865. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  55866. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  55867. _this.kernel = kernel;
  55868. _this.onApply = function (effect) {
  55869. effect.setFloat2("screenSize", _this.width, _this.height);
  55870. effect.setArray("kernel", _this.kernel);
  55871. };
  55872. return _this;
  55873. }
  55874. return ConvolutionPostProcess;
  55875. }(BABYLON.PostProcess));
  55876. // Statics
  55877. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  55878. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  55879. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  55880. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  55881. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  55882. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  55883. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  55884. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  55885. })(BABYLON || (BABYLON = {}));
  55886. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  55887. var BABYLON;
  55888. (function (BABYLON) {
  55889. var FilterPostProcess = (function (_super) {
  55890. __extends(FilterPostProcess, _super);
  55891. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  55892. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  55893. _this.kernelMatrix = kernelMatrix;
  55894. _this.onApply = function (effect) {
  55895. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  55896. };
  55897. return _this;
  55898. }
  55899. return FilterPostProcess;
  55900. }(BABYLON.PostProcess));
  55901. BABYLON.FilterPostProcess = FilterPostProcess;
  55902. })(BABYLON || (BABYLON = {}));
  55903. //# sourceMappingURL=babylon.filterPostProcess.js.map
  55904. var BABYLON;
  55905. (function (BABYLON) {
  55906. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  55907. var VolumetricLightScatteringPostProcess = (function (_super) {
  55908. __extends(VolumetricLightScatteringPostProcess, _super);
  55909. /**
  55910. * @constructor
  55911. * @param {string} name - The post-process name
  55912. * @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)
  55913. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  55914. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  55915. * @param {number} samples - The post-process quality, default 100
  55916. * @param {number} samplingMode - The post-process filtering mode
  55917. * @param {BABYLON.Engine} engine - The babylon engine
  55918. * @param {boolean} reusable - If the post-process is reusable
  55919. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  55920. */
  55921. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  55922. if (samples === void 0) { samples = 100; }
  55923. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55924. 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;
  55925. _this._screenCoordinates = BABYLON.Vector2.Zero();
  55926. /**
  55927. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  55928. * @type {Vector3}
  55929. */
  55930. _this.customMeshPosition = BABYLON.Vector3.Zero();
  55931. /**
  55932. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  55933. * @type {boolean}
  55934. */
  55935. _this.useCustomMeshPosition = false;
  55936. /**
  55937. * If the post-process should inverse the light scattering direction
  55938. * @type {boolean}
  55939. */
  55940. _this.invert = true;
  55941. /**
  55942. * Array containing the excluded meshes not rendered in the internal pass
  55943. */
  55944. _this.excludedMeshes = new Array();
  55945. /**
  55946. * Controls the overall intensity of the post-process
  55947. * @type {number}
  55948. */
  55949. _this.exposure = 0.3;
  55950. /**
  55951. * Dissipates each sample's contribution in range [0, 1]
  55952. * @type {number}
  55953. */
  55954. _this.decay = 0.96815;
  55955. /**
  55956. * Controls the overall intensity of each sample
  55957. * @type {number}
  55958. */
  55959. _this.weight = 0.58767;
  55960. /**
  55961. * Controls the density of each sample
  55962. * @type {number}
  55963. */
  55964. _this.density = 0.926;
  55965. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  55966. var engine = scene.getEngine();
  55967. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  55968. // Configure mesh
  55969. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  55970. // Configure
  55971. _this._createPass(scene, ratio.passRatio || ratio);
  55972. _this.onActivate = function (camera) {
  55973. if (!_this.isSupported) {
  55974. _this.dispose(camera);
  55975. }
  55976. _this.onActivate = null;
  55977. };
  55978. _this.onApplyObservable.add(function (effect) {
  55979. _this._updateMeshScreenCoordinates(scene);
  55980. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  55981. effect.setFloat("exposure", _this.exposure);
  55982. effect.setFloat("decay", _this.decay);
  55983. effect.setFloat("weight", _this.weight);
  55984. effect.setFloat("density", _this.density);
  55985. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  55986. });
  55987. return _this;
  55988. }
  55989. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  55990. get: function () {
  55991. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55992. return false;
  55993. },
  55994. set: function (useDiffuseColor) {
  55995. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55996. },
  55997. enumerable: true,
  55998. configurable: true
  55999. });
  56000. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  56001. return "VolumetricLightScatteringPostProcess";
  56002. };
  56003. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  56004. var mesh = subMesh.getMesh();
  56005. // Render this.mesh as default
  56006. if (mesh === this.mesh) {
  56007. return mesh.material.isReady(mesh);
  56008. }
  56009. var defines = [];
  56010. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56011. var material = subMesh.getMaterial();
  56012. var needUV = false;
  56013. // Alpha test
  56014. if (material) {
  56015. if (material.needAlphaTesting()) {
  56016. defines.push("#define ALPHATEST");
  56017. }
  56018. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56019. attribs.push(BABYLON.VertexBuffer.UVKind);
  56020. defines.push("#define UV1");
  56021. }
  56022. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56023. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56024. defines.push("#define UV2");
  56025. }
  56026. }
  56027. // Bones
  56028. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56029. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56030. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56031. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56032. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56033. }
  56034. else {
  56035. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56036. }
  56037. // Instances
  56038. if (useInstances) {
  56039. defines.push("#define INSTANCES");
  56040. attribs.push("world0");
  56041. attribs.push("world1");
  56042. attribs.push("world2");
  56043. attribs.push("world3");
  56044. }
  56045. // Get correct effect
  56046. var join = defines.join("\n");
  56047. if (this._cachedDefines !== join) {
  56048. this._cachedDefines = join;
  56049. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  56050. }
  56051. return this._volumetricLightScatteringPass.isReady();
  56052. };
  56053. /**
  56054. * Sets the new light position for light scattering effect
  56055. * @param {BABYLON.Vector3} The new custom light position
  56056. */
  56057. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  56058. this.customMeshPosition = position;
  56059. };
  56060. /**
  56061. * Returns the light position for light scattering effect
  56062. * @return {BABYLON.Vector3} The custom light position
  56063. */
  56064. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  56065. return this.customMeshPosition;
  56066. };
  56067. /**
  56068. * Disposes the internal assets and detaches the post-process from the camera
  56069. */
  56070. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  56071. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  56072. if (rttIndex !== -1) {
  56073. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  56074. }
  56075. this._volumetricLightScatteringRTT.dispose();
  56076. _super.prototype.dispose.call(this, camera);
  56077. };
  56078. /**
  56079. * Returns the render target texture used by the post-process
  56080. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  56081. */
  56082. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  56083. return this._volumetricLightScatteringRTT;
  56084. };
  56085. // Private methods
  56086. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  56087. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  56088. return true;
  56089. }
  56090. return false;
  56091. };
  56092. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  56093. var _this = this;
  56094. var engine = scene.getEngine();
  56095. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56096. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56097. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56098. this._volumetricLightScatteringRTT.renderList = null;
  56099. this._volumetricLightScatteringRTT.renderParticles = false;
  56100. var camera = this.getCamera();
  56101. if (camera) {
  56102. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  56103. }
  56104. else {
  56105. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  56106. }
  56107. // Custom render function for submeshes
  56108. var renderSubMesh = function (subMesh) {
  56109. var mesh = subMesh.getRenderingMesh();
  56110. if (_this._meshExcluded(mesh)) {
  56111. return;
  56112. }
  56113. var scene = mesh.getScene();
  56114. var engine = scene.getEngine();
  56115. // Culling
  56116. engine.setState(subMesh.getMaterial().backFaceCulling);
  56117. // Managing instances
  56118. var batch = mesh._getInstancesRenderList(subMesh._id);
  56119. if (batch.mustReturn) {
  56120. return;
  56121. }
  56122. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  56123. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  56124. var effect = _this._volumetricLightScatteringPass;
  56125. if (mesh === _this.mesh) {
  56126. if (subMesh.effect) {
  56127. effect = subMesh.effect;
  56128. }
  56129. else {
  56130. effect = subMesh.getMaterial().getEffect();
  56131. }
  56132. }
  56133. engine.enableEffect(effect);
  56134. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  56135. if (mesh === _this.mesh) {
  56136. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  56137. }
  56138. else {
  56139. var material = subMesh.getMaterial();
  56140. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  56141. // Alpha test
  56142. if (material && material.needAlphaTesting()) {
  56143. var alphaTexture = material.getAlphaTestTexture();
  56144. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  56145. if (alphaTexture) {
  56146. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  56147. }
  56148. }
  56149. // Bones
  56150. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56151. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  56152. }
  56153. }
  56154. // Draw
  56155. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  56156. }
  56157. };
  56158. // Render target texture callbacks
  56159. var savedSceneClearColor;
  56160. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  56161. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  56162. savedSceneClearColor = scene.clearColor;
  56163. scene.clearColor = sceneClearColor;
  56164. });
  56165. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  56166. scene.clearColor = savedSceneClearColor;
  56167. });
  56168. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  56169. var engine = scene.getEngine();
  56170. var index;
  56171. if (depthOnlySubMeshes.length) {
  56172. engine.setColorWrite(false);
  56173. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  56174. renderSubMesh(depthOnlySubMeshes.data[index]);
  56175. }
  56176. engine.setColorWrite(true);
  56177. }
  56178. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56179. renderSubMesh(opaqueSubMeshes.data[index]);
  56180. }
  56181. engine.setAlphaTesting(true);
  56182. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56183. renderSubMesh(alphaTestSubMeshes.data[index]);
  56184. }
  56185. engine.setAlphaTesting(false);
  56186. if (transparentSubMeshes.length) {
  56187. // Sort sub meshes
  56188. for (index = 0; index < transparentSubMeshes.length; index++) {
  56189. var submesh = transparentSubMeshes.data[index];
  56190. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  56191. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  56192. }
  56193. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  56194. sortedArray.sort(function (a, b) {
  56195. // Alpha index first
  56196. if (a._alphaIndex > b._alphaIndex) {
  56197. return 1;
  56198. }
  56199. if (a._alphaIndex < b._alphaIndex) {
  56200. return -1;
  56201. }
  56202. // Then distance to camera
  56203. if (a._distanceToCamera < b._distanceToCamera) {
  56204. return 1;
  56205. }
  56206. if (a._distanceToCamera > b._distanceToCamera) {
  56207. return -1;
  56208. }
  56209. return 0;
  56210. });
  56211. // Render sub meshes
  56212. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56213. for (index = 0; index < sortedArray.length; index++) {
  56214. renderSubMesh(sortedArray[index]);
  56215. }
  56216. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56217. }
  56218. };
  56219. };
  56220. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  56221. var transform = scene.getTransformMatrix();
  56222. var meshPosition;
  56223. if (this.useCustomMeshPosition) {
  56224. meshPosition = this.customMeshPosition;
  56225. }
  56226. else if (this.attachedNode) {
  56227. meshPosition = this.attachedNode.position;
  56228. }
  56229. else {
  56230. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  56231. }
  56232. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  56233. this._screenCoordinates.x = pos.x / this._viewPort.width;
  56234. this._screenCoordinates.y = pos.y / this._viewPort.height;
  56235. if (this.invert)
  56236. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  56237. };
  56238. // Static methods
  56239. /**
  56240. * Creates a default mesh for the Volumeric Light Scattering post-process
  56241. * @param {string} The mesh name
  56242. * @param {BABYLON.Scene} The scene where to create the mesh
  56243. * @return {BABYLON.Mesh} the default mesh
  56244. */
  56245. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  56246. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  56247. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  56248. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  56249. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  56250. mesh.material = material;
  56251. return mesh;
  56252. };
  56253. return VolumetricLightScatteringPostProcess;
  56254. }(BABYLON.PostProcess));
  56255. __decorate([
  56256. BABYLON.serializeAsVector3()
  56257. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  56258. __decorate([
  56259. BABYLON.serialize()
  56260. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  56261. __decorate([
  56262. BABYLON.serialize()
  56263. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  56264. __decorate([
  56265. BABYLON.serializeAsMeshReference()
  56266. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  56267. __decorate([
  56268. BABYLON.serialize()
  56269. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  56270. __decorate([
  56271. BABYLON.serialize()
  56272. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  56273. __decorate([
  56274. BABYLON.serialize()
  56275. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  56276. __decorate([
  56277. BABYLON.serialize()
  56278. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  56279. __decorate([
  56280. BABYLON.serialize()
  56281. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  56282. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  56283. })(BABYLON || (BABYLON = {}));
  56284. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  56285. //
  56286. // This post-process allows the modification of rendered colors by using
  56287. // a 'look-up table' (LUT). This effect is also called Color Grading.
  56288. //
  56289. // The object needs to be provided an url to a texture containing the color
  56290. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  56291. // Use an image editing software to tweak the LUT to match your needs.
  56292. //
  56293. // For an example of a color LUT, see here:
  56294. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  56295. // For explanations on color grading, see here:
  56296. // http://udn.epicgames.com/Three/ColorGrading.html
  56297. //
  56298. var BABYLON;
  56299. (function (BABYLON) {
  56300. var ColorCorrectionPostProcess = (function (_super) {
  56301. __extends(ColorCorrectionPostProcess, _super);
  56302. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  56303. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  56304. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  56305. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  56306. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56307. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56308. _this.onApply = function (effect) {
  56309. effect.setTexture("colorTable", _this._colorTableTexture);
  56310. };
  56311. return _this;
  56312. }
  56313. return ColorCorrectionPostProcess;
  56314. }(BABYLON.PostProcess));
  56315. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  56316. })(BABYLON || (BABYLON = {}));
  56317. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  56318. var BABYLON;
  56319. (function (BABYLON) {
  56320. var TonemappingOperator;
  56321. (function (TonemappingOperator) {
  56322. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  56323. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  56324. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  56325. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  56326. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  56327. ;
  56328. var TonemapPostProcess = (function (_super) {
  56329. __extends(TonemapPostProcess, _super);
  56330. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  56331. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56332. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56333. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  56334. _this._operator = _operator;
  56335. _this.exposureAdjustment = exposureAdjustment;
  56336. var defines = "#define ";
  56337. if (_this._operator === TonemappingOperator.Hable)
  56338. defines += "HABLE_TONEMAPPING";
  56339. else if (_this._operator === TonemappingOperator.Reinhard)
  56340. defines += "REINHARD_TONEMAPPING";
  56341. else if (_this._operator === TonemappingOperator.HejiDawson)
  56342. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  56343. else if (_this._operator === TonemappingOperator.Photographic)
  56344. defines += "PHOTOGRAPHIC_TONEMAPPING";
  56345. //sadly a second call to create the effect.
  56346. _this.updateEffect(defines);
  56347. _this.onApply = function (effect) {
  56348. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  56349. };
  56350. return _this;
  56351. }
  56352. return TonemapPostProcess;
  56353. }(BABYLON.PostProcess));
  56354. BABYLON.TonemapPostProcess = TonemapPostProcess;
  56355. })(BABYLON || (BABYLON = {}));
  56356. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  56357. var BABYLON;
  56358. (function (BABYLON) {
  56359. var DisplayPassPostProcess = (function (_super) {
  56360. __extends(DisplayPassPostProcess, _super);
  56361. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  56362. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  56363. }
  56364. return DisplayPassPostProcess;
  56365. }(BABYLON.PostProcess));
  56366. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  56367. })(BABYLON || (BABYLON = {}));
  56368. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  56369. var BABYLON;
  56370. (function (BABYLON) {
  56371. var HighlightsPostProcess = (function (_super) {
  56372. __extends(HighlightsPostProcess, _super);
  56373. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  56374. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56375. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  56376. }
  56377. return HighlightsPostProcess;
  56378. }(BABYLON.PostProcess));
  56379. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  56380. })(BABYLON || (BABYLON = {}));
  56381. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  56382. var BABYLON;
  56383. (function (BABYLON) {
  56384. var ImageProcessingPostProcess = (function (_super) {
  56385. __extends(ImageProcessingPostProcess, _super);
  56386. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  56387. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56388. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  56389. _this._fromLinearSpace = true;
  56390. /**
  56391. * Defines cache preventing GC.
  56392. */
  56393. _this._defines = {
  56394. IMAGEPROCESSING: false,
  56395. VIGNETTE: false,
  56396. VIGNETTEBLENDMODEMULTIPLY: false,
  56397. VIGNETTEBLENDMODEOPAQUE: false,
  56398. TONEMAPPING: false,
  56399. CONTRAST: false,
  56400. COLORCURVES: false,
  56401. COLORGRADING: false,
  56402. FROMLINEARSPACE: false,
  56403. SAMPLER3DGREENDEPTH: false,
  56404. SAMPLER3DBGRMAP: false,
  56405. IMAGEPROCESSINGPOSTPROCESS: false,
  56406. EXPOSURE: false,
  56407. };
  56408. // Setup the default processing configuration to the scene.
  56409. _this._attachImageProcessingConfiguration(null, true);
  56410. _this.imageProcessingConfiguration.applyByPostProcess = true;
  56411. _this.onApply = function (effect) {
  56412. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  56413. };
  56414. return _this;
  56415. }
  56416. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  56417. /**
  56418. * Gets the image processing configuration used either in this material.
  56419. */
  56420. get: function () {
  56421. return this._imageProcessingConfiguration;
  56422. },
  56423. /**
  56424. * Sets the Default image processing configuration used either in the this material.
  56425. *
  56426. * If sets to null, the scene one is in use.
  56427. */
  56428. set: function (value) {
  56429. this._attachImageProcessingConfiguration(value);
  56430. },
  56431. enumerable: true,
  56432. configurable: true
  56433. });
  56434. /**
  56435. * Attaches a new image processing configuration to the PBR Material.
  56436. * @param configuration
  56437. */
  56438. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  56439. var _this = this;
  56440. if (doNotBuild === void 0) { doNotBuild = false; }
  56441. if (configuration === this._imageProcessingConfiguration) {
  56442. return;
  56443. }
  56444. // Detaches observer.
  56445. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  56446. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  56447. }
  56448. // Pick the scene configuration if needed.
  56449. if (!configuration) {
  56450. var scene = null;
  56451. var engine = this.getEngine();
  56452. var camera = this.getCamera();
  56453. if (camera) {
  56454. scene = camera.getScene();
  56455. }
  56456. else if (engine && engine.scenes) {
  56457. var scenes = engine.scenes;
  56458. scene = scenes[scenes.length - 1];
  56459. }
  56460. else {
  56461. scene = BABYLON.Engine.LastCreatedScene;
  56462. }
  56463. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  56464. }
  56465. else {
  56466. this._imageProcessingConfiguration = configuration;
  56467. }
  56468. // Attaches observer.
  56469. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  56470. _this._updateParameters();
  56471. });
  56472. // Ensure the effect will be rebuilt.
  56473. if (!doNotBuild) {
  56474. this._updateParameters();
  56475. }
  56476. };
  56477. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  56478. /**
  56479. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  56480. */
  56481. get: function () {
  56482. return this.imageProcessingConfiguration.colorCurves;
  56483. },
  56484. /**
  56485. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  56486. */
  56487. set: function (value) {
  56488. this.imageProcessingConfiguration.colorCurves = value;
  56489. },
  56490. enumerable: true,
  56491. configurable: true
  56492. });
  56493. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  56494. /**
  56495. * Gets wether the color curves effect is enabled.
  56496. */
  56497. get: function () {
  56498. return this.imageProcessingConfiguration.colorCurvesEnabled;
  56499. },
  56500. /**
  56501. * Sets wether the color curves effect is enabled.
  56502. */
  56503. set: function (value) {
  56504. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  56505. },
  56506. enumerable: true,
  56507. configurable: true
  56508. });
  56509. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  56510. /**
  56511. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  56512. */
  56513. get: function () {
  56514. return this.imageProcessingConfiguration.colorGradingTexture;
  56515. },
  56516. /**
  56517. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  56518. */
  56519. set: function (value) {
  56520. this.imageProcessingConfiguration.colorGradingTexture = value;
  56521. },
  56522. enumerable: true,
  56523. configurable: true
  56524. });
  56525. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  56526. /**
  56527. * Gets wether the color grading effect is enabled.
  56528. */
  56529. get: function () {
  56530. return this.imageProcessingConfiguration.colorGradingEnabled;
  56531. },
  56532. /**
  56533. * Gets wether the color grading effect is enabled.
  56534. */
  56535. set: function (value) {
  56536. this.imageProcessingConfiguration.colorGradingEnabled = value;
  56537. },
  56538. enumerable: true,
  56539. configurable: true
  56540. });
  56541. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  56542. /**
  56543. * Gets exposure used in the effect.
  56544. */
  56545. get: function () {
  56546. return this.imageProcessingConfiguration.exposure;
  56547. },
  56548. /**
  56549. * Sets exposure used in the effect.
  56550. */
  56551. set: function (value) {
  56552. this.imageProcessingConfiguration.exposure = value;
  56553. },
  56554. enumerable: true,
  56555. configurable: true
  56556. });
  56557. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  56558. /**
  56559. * Gets wether tonemapping is enabled or not.
  56560. */
  56561. get: function () {
  56562. return this._imageProcessingConfiguration.toneMappingEnabled;
  56563. },
  56564. /**
  56565. * Sets wether tonemapping is enabled or not
  56566. */
  56567. set: function (value) {
  56568. this._imageProcessingConfiguration.toneMappingEnabled = value;
  56569. },
  56570. enumerable: true,
  56571. configurable: true
  56572. });
  56573. ;
  56574. ;
  56575. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  56576. /**
  56577. * Gets contrast used in the effect.
  56578. */
  56579. get: function () {
  56580. return this.imageProcessingConfiguration.contrast;
  56581. },
  56582. /**
  56583. * Sets contrast used in the effect.
  56584. */
  56585. set: function (value) {
  56586. this.imageProcessingConfiguration.contrast = value;
  56587. },
  56588. enumerable: true,
  56589. configurable: true
  56590. });
  56591. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  56592. /**
  56593. * Gets Vignette stretch size.
  56594. */
  56595. get: function () {
  56596. return this.imageProcessingConfiguration.vignetteStretch;
  56597. },
  56598. /**
  56599. * Sets Vignette stretch size.
  56600. */
  56601. set: function (value) {
  56602. this.imageProcessingConfiguration.vignetteStretch = value;
  56603. },
  56604. enumerable: true,
  56605. configurable: true
  56606. });
  56607. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  56608. /**
  56609. * Gets Vignette centre X Offset.
  56610. */
  56611. get: function () {
  56612. return this.imageProcessingConfiguration.vignetteCentreX;
  56613. },
  56614. /**
  56615. * Sets Vignette centre X Offset.
  56616. */
  56617. set: function (value) {
  56618. this.imageProcessingConfiguration.vignetteCentreX = value;
  56619. },
  56620. enumerable: true,
  56621. configurable: true
  56622. });
  56623. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  56624. /**
  56625. * Gets Vignette centre Y Offset.
  56626. */
  56627. get: function () {
  56628. return this.imageProcessingConfiguration.vignetteCentreY;
  56629. },
  56630. /**
  56631. * Sets Vignette centre Y Offset.
  56632. */
  56633. set: function (value) {
  56634. this.imageProcessingConfiguration.vignetteCentreY = value;
  56635. },
  56636. enumerable: true,
  56637. configurable: true
  56638. });
  56639. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  56640. /**
  56641. * Gets Vignette weight or intensity of the vignette effect.
  56642. */
  56643. get: function () {
  56644. return this.imageProcessingConfiguration.vignetteWeight;
  56645. },
  56646. /**
  56647. * Sets Vignette weight or intensity of the vignette effect.
  56648. */
  56649. set: function (value) {
  56650. this.imageProcessingConfiguration.vignetteWeight = value;
  56651. },
  56652. enumerable: true,
  56653. configurable: true
  56654. });
  56655. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  56656. /**
  56657. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  56658. * if vignetteEnabled is set to true.
  56659. */
  56660. get: function () {
  56661. return this.imageProcessingConfiguration.vignetteColor;
  56662. },
  56663. /**
  56664. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  56665. * if vignetteEnabled is set to true.
  56666. */
  56667. set: function (value) {
  56668. this.imageProcessingConfiguration.vignetteColor = value;
  56669. },
  56670. enumerable: true,
  56671. configurable: true
  56672. });
  56673. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  56674. /**
  56675. * Gets Camera field of view used by the Vignette effect.
  56676. */
  56677. get: function () {
  56678. return this.imageProcessingConfiguration.vignetteCameraFov;
  56679. },
  56680. /**
  56681. * Sets Camera field of view used by the Vignette effect.
  56682. */
  56683. set: function (value) {
  56684. this.imageProcessingConfiguration.vignetteCameraFov = value;
  56685. },
  56686. enumerable: true,
  56687. configurable: true
  56688. });
  56689. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  56690. /**
  56691. * Gets the vignette blend mode allowing different kind of effect.
  56692. */
  56693. get: function () {
  56694. return this.imageProcessingConfiguration.vignetteBlendMode;
  56695. },
  56696. /**
  56697. * Sets the vignette blend mode allowing different kind of effect.
  56698. */
  56699. set: function (value) {
  56700. this.imageProcessingConfiguration.vignetteBlendMode = value;
  56701. },
  56702. enumerable: true,
  56703. configurable: true
  56704. });
  56705. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  56706. /**
  56707. * Gets wether the vignette effect is enabled.
  56708. */
  56709. get: function () {
  56710. return this.imageProcessingConfiguration.vignetteEnabled;
  56711. },
  56712. /**
  56713. * Sets wether the vignette effect is enabled.
  56714. */
  56715. set: function (value) {
  56716. this.imageProcessingConfiguration.vignetteEnabled = value;
  56717. },
  56718. enumerable: true,
  56719. configurable: true
  56720. });
  56721. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  56722. /**
  56723. * Gets wether the input of the processing is in Gamma or Linear Space.
  56724. */
  56725. get: function () {
  56726. return this._fromLinearSpace;
  56727. },
  56728. /**
  56729. * Sets wether the input of the processing is in Gamma or Linear Space.
  56730. */
  56731. set: function (value) {
  56732. if (this._fromLinearSpace === value) {
  56733. return;
  56734. }
  56735. this._fromLinearSpace = value;
  56736. this._updateParameters();
  56737. },
  56738. enumerable: true,
  56739. configurable: true
  56740. });
  56741. ImageProcessingPostProcess.prototype.getClassName = function () {
  56742. return "ImageProcessingPostProcess";
  56743. };
  56744. ImageProcessingPostProcess.prototype._updateParameters = function () {
  56745. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  56746. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  56747. var defines = "";
  56748. for (var define in this._defines) {
  56749. if (this._defines[define]) {
  56750. defines += "#define " + define + ";\r\n";
  56751. }
  56752. }
  56753. var samplers = ["textureSampler"];
  56754. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  56755. var uniforms = ["scale"];
  56756. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  56757. this.updateEffect(defines, uniforms, samplers);
  56758. };
  56759. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  56760. _super.prototype.dispose.call(this, camera);
  56761. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  56762. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  56763. }
  56764. this.imageProcessingConfiguration.applyByPostProcess = false;
  56765. };
  56766. return ImageProcessingPostProcess;
  56767. }(BABYLON.PostProcess));
  56768. __decorate([
  56769. BABYLON.serialize()
  56770. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  56771. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  56772. })(BABYLON || (BABYLON = {}));
  56773. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  56774. var BABYLON;
  56775. (function (BABYLON) {
  56776. var BlurPostProcess = (function (_super) {
  56777. __extends(BlurPostProcess, _super);
  56778. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  56779. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56780. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56781. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  56782. _this.direction = direction;
  56783. _this._packedFloat = false;
  56784. _this.onApplyObservable.add(function (effect) {
  56785. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  56786. });
  56787. _this.kernel = kernel;
  56788. return _this;
  56789. }
  56790. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  56791. /**
  56792. * Gets the length in pixels of the blur sample region
  56793. */
  56794. get: function () {
  56795. return this._idealKernel;
  56796. },
  56797. /**
  56798. * Sets the length in pixels of the blur sample region
  56799. */
  56800. set: function (v) {
  56801. if (this._idealKernel === v) {
  56802. return;
  56803. }
  56804. v = Math.max(v, 1);
  56805. this._idealKernel = v;
  56806. this._kernel = this._nearestBestKernel(v);
  56807. this._updateParameters();
  56808. },
  56809. enumerable: true,
  56810. configurable: true
  56811. });
  56812. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  56813. /**
  56814. * Gets wether or not the blur is unpacking/repacking floats
  56815. */
  56816. get: function () {
  56817. return this._packedFloat;
  56818. },
  56819. /**
  56820. * Sets wether or not the blur needs to unpack/repack floats
  56821. */
  56822. set: function (v) {
  56823. if (this._packedFloat === v) {
  56824. return;
  56825. }
  56826. this._packedFloat = v;
  56827. this._updateParameters();
  56828. },
  56829. enumerable: true,
  56830. configurable: true
  56831. });
  56832. BlurPostProcess.prototype._updateParameters = function () {
  56833. // Generate sampling offsets and weights
  56834. var N = this._kernel;
  56835. var centerIndex = (N - 1) / 2;
  56836. // Generate Gaussian sampling weights over kernel
  56837. var offsets = [];
  56838. var weights = [];
  56839. var totalWeight = 0;
  56840. for (var i = 0; i < N; i++) {
  56841. var u = i / (N - 1);
  56842. var w = this._gaussianWeight(u * 2.0 - 1);
  56843. offsets[i] = (i - centerIndex);
  56844. weights[i] = w;
  56845. totalWeight += w;
  56846. }
  56847. // Normalize weights
  56848. for (var i = 0; i < weights.length; i++) {
  56849. weights[i] /= totalWeight;
  56850. }
  56851. // Optimize: combine samples to take advantage of hardware linear sampling
  56852. // Walk from left to center, combining pairs (symmetrically)
  56853. var linearSamplingWeights = [];
  56854. var linearSamplingOffsets = [];
  56855. var linearSamplingMap = [];
  56856. for (var i = 0; i <= centerIndex; i += 2) {
  56857. var j = Math.min(i + 1, Math.floor(centerIndex));
  56858. var singleCenterSample = i === j;
  56859. if (singleCenterSample) {
  56860. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  56861. }
  56862. else {
  56863. var sharedCell = j === centerIndex;
  56864. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  56865. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  56866. if (offsetLinear === 0) {
  56867. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  56868. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  56869. }
  56870. else {
  56871. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  56872. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  56873. }
  56874. }
  56875. }
  56876. for (var i = 0; i < linearSamplingMap.length; i++) {
  56877. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  56878. linearSamplingWeights[i] = linearSamplingMap[i].w;
  56879. }
  56880. // Replace with optimized
  56881. offsets = linearSamplingOffsets;
  56882. weights = linearSamplingWeights;
  56883. // Generate shaders
  56884. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  56885. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  56886. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  56887. var defines = "";
  56888. for (var i = 0; i < varyingCount; i++) {
  56889. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  56890. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  56891. }
  56892. var depCount = 0;
  56893. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  56894. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  56895. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  56896. depCount++;
  56897. }
  56898. if (this.packedFloat) {
  56899. defines += "#define PACKEDFLOAT 1";
  56900. }
  56901. this.updateEffect(defines, null, null, {
  56902. varyingCount: varyingCount,
  56903. depCount: depCount
  56904. });
  56905. };
  56906. /**
  56907. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  56908. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  56909. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  56910. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  56911. * The gaps between physical kernels are compensated for in the weighting of the samples
  56912. * @param idealKernel Ideal blur kernel.
  56913. * @return Nearest best kernel.
  56914. */
  56915. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  56916. var v = Math.round(idealKernel);
  56917. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  56918. var k = _a[_i];
  56919. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  56920. return Math.max(k, 3);
  56921. }
  56922. }
  56923. return Math.max(v, 3);
  56924. };
  56925. /**
  56926. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  56927. * @param x The point on the Gaussian distribution to sample.
  56928. * @return the value of the Gaussian function at x.
  56929. */
  56930. BlurPostProcess.prototype._gaussianWeight = function (x) {
  56931. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  56932. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  56933. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  56934. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  56935. // truncated at around 1.3% of peak strength.
  56936. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  56937. var sigma = (1 / 3);
  56938. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  56939. var exponent = -((x * x) / (2.0 * sigma * sigma));
  56940. var weight = (1.0 / denominator) * Math.exp(exponent);
  56941. return weight;
  56942. };
  56943. /**
  56944. * Generates a string that can be used as a floating point number in GLSL.
  56945. * @param x Value to print.
  56946. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  56947. * @return GLSL float string.
  56948. */
  56949. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  56950. if (decimalFigures === void 0) { decimalFigures = 8; }
  56951. return x.toFixed(decimalFigures).replace(/0+$/, '');
  56952. };
  56953. return BlurPostProcess;
  56954. }(BABYLON.PostProcess));
  56955. BABYLON.BlurPostProcess = BlurPostProcess;
  56956. })(BABYLON || (BABYLON = {}));
  56957. //# sourceMappingURL=babylon.blurPostProcess.js.map
  56958. /// <reference path="..\babylon.node.ts" />
  56959. var BABYLON;
  56960. (function (BABYLON) {
  56961. var Bone = (function (_super) {
  56962. __extends(Bone, _super);
  56963. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  56964. if (parentBone === void 0) { parentBone = null; }
  56965. var _this = _super.call(this, name, skeleton.getScene()) || this;
  56966. _this.name = name;
  56967. _this.children = new Array();
  56968. _this.animations = new Array();
  56969. _this._worldTransform = new BABYLON.Matrix();
  56970. _this._absoluteTransform = new BABYLON.Matrix();
  56971. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  56972. _this._scaleMatrix = BABYLON.Matrix.Identity();
  56973. _this._scaleVector = BABYLON.Vector3.One();
  56974. _this._negateScaleChildren = BABYLON.Vector3.One();
  56975. _this._scalingDeterminant = 1;
  56976. _this._skeleton = skeleton;
  56977. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  56978. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  56979. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  56980. _this._index = index;
  56981. skeleton.bones.push(_this);
  56982. _this.setParent(parentBone, false);
  56983. _this._updateDifferenceMatrix();
  56984. return _this;
  56985. }
  56986. Object.defineProperty(Bone.prototype, "_matrix", {
  56987. get: function () {
  56988. return this._localMatrix;
  56989. },
  56990. set: function (val) {
  56991. if (this._localMatrix) {
  56992. this._localMatrix.copyFrom(val);
  56993. }
  56994. else {
  56995. this._localMatrix = val;
  56996. }
  56997. },
  56998. enumerable: true,
  56999. configurable: true
  57000. });
  57001. // Members
  57002. Bone.prototype.getSkeleton = function () {
  57003. return this._skeleton;
  57004. };
  57005. Bone.prototype.getParent = function () {
  57006. return this._parent;
  57007. };
  57008. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  57009. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  57010. if (this._parent === parent) {
  57011. return;
  57012. }
  57013. if (this._parent) {
  57014. var index = this._parent.children.indexOf(this);
  57015. if (index !== -1) {
  57016. this._parent.children.splice(index);
  57017. }
  57018. }
  57019. this._parent = parent;
  57020. if (this._parent) {
  57021. this._parent.children.push(this);
  57022. }
  57023. if (updateDifferenceMatrix) {
  57024. this._updateDifferenceMatrix();
  57025. }
  57026. };
  57027. Bone.prototype.getLocalMatrix = function () {
  57028. return this._localMatrix;
  57029. };
  57030. Bone.prototype.getBaseMatrix = function () {
  57031. return this._baseMatrix;
  57032. };
  57033. Bone.prototype.getRestPose = function () {
  57034. return this._restPose;
  57035. };
  57036. Bone.prototype.returnToRest = function () {
  57037. this.updateMatrix(this._restPose.clone());
  57038. };
  57039. Bone.prototype.getWorldMatrix = function () {
  57040. return this._worldTransform;
  57041. };
  57042. Bone.prototype.getInvertedAbsoluteTransform = function () {
  57043. return this._invertedAbsoluteTransform;
  57044. };
  57045. Bone.prototype.getAbsoluteTransform = function () {
  57046. return this._absoluteTransform;
  57047. };
  57048. Object.defineProperty(Bone.prototype, "position", {
  57049. // Properties (matches AbstractMesh properties)
  57050. get: function () {
  57051. return this.getPosition();
  57052. },
  57053. set: function (newPosition) {
  57054. this.setPosition(newPosition);
  57055. },
  57056. enumerable: true,
  57057. configurable: true
  57058. });
  57059. Object.defineProperty(Bone.prototype, "rotation", {
  57060. get: function () {
  57061. return this.getRotation();
  57062. },
  57063. set: function (newRotation) {
  57064. this.setRotation(newRotation);
  57065. },
  57066. enumerable: true,
  57067. configurable: true
  57068. });
  57069. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  57070. get: function () {
  57071. return this.getRotationQuaternion();
  57072. },
  57073. set: function (newRotation) {
  57074. this.setRotationQuaternion(newRotation);
  57075. },
  57076. enumerable: true,
  57077. configurable: true
  57078. });
  57079. Object.defineProperty(Bone.prototype, "scaling", {
  57080. get: function () {
  57081. return this.getScale();
  57082. },
  57083. set: function (newScaling) {
  57084. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  57085. },
  57086. enumerable: true,
  57087. configurable: true
  57088. });
  57089. // Methods
  57090. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  57091. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  57092. this._baseMatrix = matrix.clone();
  57093. this._localMatrix = matrix.clone();
  57094. this._skeleton._markAsDirty();
  57095. if (updateDifferenceMatrix) {
  57096. this._updateDifferenceMatrix();
  57097. }
  57098. };
  57099. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  57100. if (!rootMatrix) {
  57101. rootMatrix = this._baseMatrix;
  57102. }
  57103. if (this._parent) {
  57104. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  57105. }
  57106. else {
  57107. this._absoluteTransform.copyFrom(rootMatrix);
  57108. }
  57109. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  57110. for (var index = 0; index < this.children.length; index++) {
  57111. this.children[index]._updateDifferenceMatrix();
  57112. }
  57113. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  57114. };
  57115. Bone.prototype.markAsDirty = function () {
  57116. this._currentRenderId++;
  57117. this._skeleton._markAsDirty();
  57118. };
  57119. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  57120. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  57121. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  57122. // all animation may be coming from a library skeleton, so may need to create animation
  57123. if (this.animations.length === 0) {
  57124. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  57125. this.animations[0].setKeys([]);
  57126. }
  57127. // get animation info / verify there is such a range from the source bone
  57128. var sourceRange = source.animations[0].getRange(rangeName);
  57129. if (!sourceRange) {
  57130. return false;
  57131. }
  57132. var from = sourceRange.from;
  57133. var to = sourceRange.to;
  57134. var sourceKeys = source.animations[0].getKeys();
  57135. // rescaling prep
  57136. var sourceBoneLength = source.length;
  57137. var sourceParent = source.getParent();
  57138. var parent = this.getParent();
  57139. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  57140. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  57141. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  57142. var destKeys = this.animations[0].getKeys();
  57143. // loop vars declaration
  57144. var orig;
  57145. var origTranslation;
  57146. var mat;
  57147. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  57148. orig = sourceKeys[key];
  57149. if (orig.frame >= from && orig.frame <= to) {
  57150. if (rescaleAsRequired) {
  57151. mat = orig.value.clone();
  57152. // scale based on parent ratio, when bone has parent
  57153. if (parentScalingReqd) {
  57154. origTranslation = mat.getTranslation();
  57155. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  57156. // scale based on skeleton dimension ratio when root bone, and value is passed
  57157. }
  57158. else if (dimensionsScalingReqd) {
  57159. origTranslation = mat.getTranslation();
  57160. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  57161. // use original when root bone, and no data for skelDimensionsRatio
  57162. }
  57163. else {
  57164. mat = orig.value;
  57165. }
  57166. }
  57167. else {
  57168. mat = orig.value;
  57169. }
  57170. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  57171. }
  57172. }
  57173. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  57174. return true;
  57175. };
  57176. /**
  57177. * Translate the bone in local or world space.
  57178. * @param vec The amount to translate the bone.
  57179. * @param space The space that the translation is in.
  57180. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57181. */
  57182. Bone.prototype.translate = function (vec, space, mesh) {
  57183. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57184. var lm = this.getLocalMatrix();
  57185. if (space == BABYLON.Space.LOCAL) {
  57186. lm.m[12] += vec.x;
  57187. lm.m[13] += vec.y;
  57188. lm.m[14] += vec.z;
  57189. }
  57190. else {
  57191. var wm;
  57192. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57193. if (mesh) {
  57194. wm = mesh.getWorldMatrix();
  57195. }
  57196. this._skeleton.computeAbsoluteTransforms();
  57197. var tmat = Bone._tmpMats[0];
  57198. var tvec = Bone._tmpVecs[0];
  57199. if (mesh) {
  57200. tmat.copyFrom(this._parent.getAbsoluteTransform());
  57201. tmat.multiplyToRef(wm, tmat);
  57202. }
  57203. else {
  57204. tmat.copyFrom(this._parent.getAbsoluteTransform());
  57205. }
  57206. tmat.m[12] = 0;
  57207. tmat.m[13] = 0;
  57208. tmat.m[14] = 0;
  57209. tmat.invert();
  57210. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  57211. lm.m[12] += tvec.x;
  57212. lm.m[13] += tvec.y;
  57213. lm.m[14] += tvec.z;
  57214. }
  57215. this.markAsDirty();
  57216. };
  57217. /**
  57218. * Set the postion of the bone in local or world space.
  57219. * @param position The position to set the bone.
  57220. * @param space The space that the position is in.
  57221. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57222. */
  57223. Bone.prototype.setPosition = function (position, space, mesh) {
  57224. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57225. var lm = this.getLocalMatrix();
  57226. if (space == BABYLON.Space.LOCAL) {
  57227. lm.m[12] = position.x;
  57228. lm.m[13] = position.y;
  57229. lm.m[14] = position.z;
  57230. }
  57231. else {
  57232. var wm;
  57233. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57234. if (mesh) {
  57235. wm = mesh.getWorldMatrix();
  57236. }
  57237. this._skeleton.computeAbsoluteTransforms();
  57238. var tmat = Bone._tmpMats[0];
  57239. var vec = Bone._tmpVecs[0];
  57240. if (mesh) {
  57241. tmat.copyFrom(this._parent.getAbsoluteTransform());
  57242. tmat.multiplyToRef(wm, tmat);
  57243. }
  57244. else {
  57245. tmat.copyFrom(this._parent.getAbsoluteTransform());
  57246. }
  57247. tmat.invert();
  57248. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  57249. lm.m[12] = vec.x;
  57250. lm.m[13] = vec.y;
  57251. lm.m[14] = vec.z;
  57252. }
  57253. this.markAsDirty();
  57254. };
  57255. /**
  57256. * Set the absolute postion of the bone (world space).
  57257. * @param position The position to set the bone.
  57258. * @param mesh The mesh that this bone is attached to.
  57259. */
  57260. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  57261. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  57262. };
  57263. /**
  57264. * Set the scale of the bone on the x, y and z axes.
  57265. * @param x The scale of the bone on the x axis.
  57266. * @param x The scale of the bone on the y axis.
  57267. * @param z The scale of the bone on the z axis.
  57268. * @param scaleChildren Set this to true if children of the bone should be scaled.
  57269. */
  57270. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  57271. if (scaleChildren === void 0) { scaleChildren = false; }
  57272. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  57273. if (!scaleChildren) {
  57274. this._negateScaleChildren.x = 1 / x;
  57275. this._negateScaleChildren.y = 1 / y;
  57276. this._negateScaleChildren.z = 1 / z;
  57277. }
  57278. this._syncScaleVector();
  57279. }
  57280. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  57281. };
  57282. /**
  57283. * Scale the bone on the x, y and z axes.
  57284. * @param x The amount to scale the bone on the x axis.
  57285. * @param x The amount to scale the bone on the y axis.
  57286. * @param z The amount to scale the bone on the z axis.
  57287. * @param scaleChildren Set this to true if children of the bone should be scaled.
  57288. */
  57289. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  57290. if (scaleChildren === void 0) { scaleChildren = false; }
  57291. var locMat = this.getLocalMatrix();
  57292. var origLocMat = Bone._tmpMats[0];
  57293. origLocMat.copyFrom(locMat);
  57294. var origLocMatInv = Bone._tmpMats[1];
  57295. origLocMatInv.copyFrom(origLocMat);
  57296. origLocMatInv.invert();
  57297. var scaleMat = Bone._tmpMats[2];
  57298. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  57299. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  57300. this._scaleVector.x *= x;
  57301. this._scaleVector.y *= y;
  57302. this._scaleVector.z *= z;
  57303. locMat.multiplyToRef(origLocMatInv, locMat);
  57304. locMat.multiplyToRef(scaleMat, locMat);
  57305. locMat.multiplyToRef(origLocMat, locMat);
  57306. var parent = this.getParent();
  57307. if (parent) {
  57308. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  57309. }
  57310. else {
  57311. this.getAbsoluteTransform().copyFrom(locMat);
  57312. }
  57313. var len = this.children.length;
  57314. scaleMat.invert();
  57315. for (var i = 0; i < len; i++) {
  57316. var child = this.children[i];
  57317. var cm = child.getLocalMatrix();
  57318. cm.multiplyToRef(scaleMat, cm);
  57319. var lm = child.getLocalMatrix();
  57320. lm.m[12] *= x;
  57321. lm.m[13] *= y;
  57322. lm.m[14] *= z;
  57323. }
  57324. this.computeAbsoluteTransforms();
  57325. if (scaleChildren) {
  57326. for (var i = 0; i < len; i++) {
  57327. this.children[i].scale(x, y, z, scaleChildren);
  57328. }
  57329. }
  57330. this.markAsDirty();
  57331. };
  57332. /**
  57333. * Set the yaw, pitch, and roll of the bone in local or world space.
  57334. * @param yaw The rotation of the bone on the y axis.
  57335. * @param pitch The rotation of the bone on the x axis.
  57336. * @param roll The rotation of the bone on the z axis.
  57337. * @param space The space that the axes of rotation are in.
  57338. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57339. */
  57340. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  57341. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57342. var rotMat = Bone._tmpMats[0];
  57343. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  57344. var rotMatInv = Bone._tmpMats[1];
  57345. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57346. rotMatInv.multiplyToRef(rotMat, rotMat);
  57347. this._rotateWithMatrix(rotMat, space, mesh);
  57348. };
  57349. /**
  57350. * Rotate the bone on an axis in local or world space.
  57351. * @param axis The axis to rotate the bone on.
  57352. * @param amount The amount to rotate the bone.
  57353. * @param space The space that the axis is in.
  57354. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57355. */
  57356. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  57357. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57358. var rmat = Bone._tmpMats[0];
  57359. rmat.m[12] = 0;
  57360. rmat.m[13] = 0;
  57361. rmat.m[14] = 0;
  57362. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  57363. this._rotateWithMatrix(rmat, space, mesh);
  57364. };
  57365. /**
  57366. * Set the rotation of the bone to a particular axis angle in local or world space.
  57367. * @param axis The axis to rotate the bone on.
  57368. * @param angle The angle that the bone should be rotated to.
  57369. * @param space The space that the axis is in.
  57370. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57371. */
  57372. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  57373. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57374. var rotMat = Bone._tmpMats[0];
  57375. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  57376. var rotMatInv = Bone._tmpMats[1];
  57377. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57378. rotMatInv.multiplyToRef(rotMat, rotMat);
  57379. this._rotateWithMatrix(rotMat, space, mesh);
  57380. };
  57381. /**
  57382. * Set the euler rotation of the bone in local of world space.
  57383. * @param rotation The euler rotation that the bone should be set to.
  57384. * @param space The space that the rotation is in.
  57385. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57386. */
  57387. Bone.prototype.setRotation = function (rotation, space, mesh) {
  57388. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57389. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  57390. };
  57391. /**
  57392. * Set the quaternion rotation of the bone in local of world space.
  57393. * @param quat The quaternion rotation that the bone should be set to.
  57394. * @param space The space that the rotation is in.
  57395. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57396. */
  57397. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  57398. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57399. var rotMatInv = Bone._tmpMats[0];
  57400. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57401. var rotMat = Bone._tmpMats[1];
  57402. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  57403. rotMatInv.multiplyToRef(rotMat, rotMat);
  57404. this._rotateWithMatrix(rotMat, space, mesh);
  57405. };
  57406. /**
  57407. * Set the rotation matrix of the bone in local of world space.
  57408. * @param rotMat The rotation matrix that the bone should be set to.
  57409. * @param space The space that the rotation is in.
  57410. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57411. */
  57412. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  57413. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57414. var rotMatInv = Bone._tmpMats[0];
  57415. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57416. var rotMat2 = Bone._tmpMats[1];
  57417. rotMat2.copyFrom(rotMat);
  57418. rotMatInv.multiplyToRef(rotMat, rotMat2);
  57419. this._rotateWithMatrix(rotMat2, space, mesh);
  57420. };
  57421. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  57422. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57423. var lmat = this.getLocalMatrix();
  57424. var lx = lmat.m[12];
  57425. var ly = lmat.m[13];
  57426. var lz = lmat.m[14];
  57427. var parent = this.getParent();
  57428. var parentScale = Bone._tmpMats[3];
  57429. var parentScaleInv = Bone._tmpMats[4];
  57430. if (parent) {
  57431. if (space == BABYLON.Space.WORLD) {
  57432. if (mesh) {
  57433. parentScale.copyFrom(mesh.getWorldMatrix());
  57434. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  57435. }
  57436. else {
  57437. parentScale.copyFrom(parent.getAbsoluteTransform());
  57438. }
  57439. }
  57440. else {
  57441. parentScale = parent._scaleMatrix;
  57442. }
  57443. parentScaleInv.copyFrom(parentScale);
  57444. parentScaleInv.invert();
  57445. lmat.multiplyToRef(parentScale, lmat);
  57446. lmat.multiplyToRef(rmat, lmat);
  57447. lmat.multiplyToRef(parentScaleInv, lmat);
  57448. }
  57449. else {
  57450. if (space == BABYLON.Space.WORLD && mesh) {
  57451. parentScale.copyFrom(mesh.getWorldMatrix());
  57452. parentScaleInv.copyFrom(parentScale);
  57453. parentScaleInv.invert();
  57454. lmat.multiplyToRef(parentScale, lmat);
  57455. lmat.multiplyToRef(rmat, lmat);
  57456. lmat.multiplyToRef(parentScaleInv, lmat);
  57457. }
  57458. else {
  57459. lmat.multiplyToRef(rmat, lmat);
  57460. }
  57461. }
  57462. lmat.m[12] = lx;
  57463. lmat.m[13] = ly;
  57464. lmat.m[14] = lz;
  57465. this.computeAbsoluteTransforms();
  57466. this.markAsDirty();
  57467. };
  57468. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  57469. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57470. if (space == BABYLON.Space.WORLD) {
  57471. var scaleMatrix = Bone._tmpMats[2];
  57472. scaleMatrix.copyFrom(this._scaleMatrix);
  57473. rotMatInv.copyFrom(this.getAbsoluteTransform());
  57474. if (mesh) {
  57475. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  57476. var meshScale = Bone._tmpMats[3];
  57477. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  57478. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  57479. }
  57480. rotMatInv.invert();
  57481. scaleMatrix.m[0] *= this._scalingDeterminant;
  57482. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  57483. }
  57484. else {
  57485. rotMatInv.copyFrom(this.getLocalMatrix());
  57486. rotMatInv.invert();
  57487. var scaleMatrix = Bone._tmpMats[2];
  57488. scaleMatrix.copyFrom(this._scaleMatrix);
  57489. if (this._parent) {
  57490. var pscaleMatrix = Bone._tmpMats[3];
  57491. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  57492. pscaleMatrix.invert();
  57493. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  57494. }
  57495. else {
  57496. scaleMatrix.m[0] *= this._scalingDeterminant;
  57497. }
  57498. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  57499. }
  57500. };
  57501. /**
  57502. * Get the scale of the bone
  57503. * @returns the scale of the bone
  57504. */
  57505. Bone.prototype.getScale = function () {
  57506. return this._scaleVector.clone();
  57507. };
  57508. /**
  57509. * Copy the scale of the bone to a vector3.
  57510. * @param result The vector3 to copy the scale to
  57511. */
  57512. Bone.prototype.getScaleToRef = function (result) {
  57513. result.copyFrom(this._scaleVector);
  57514. };
  57515. /**
  57516. * Get the position of the bone in local or world space.
  57517. * @param space The space that the returned position is in.
  57518. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57519. * @returns The position of the bone
  57520. */
  57521. Bone.prototype.getPosition = function (space, mesh) {
  57522. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57523. var pos = BABYLON.Vector3.Zero();
  57524. this.getPositionToRef(space, mesh, pos);
  57525. return pos;
  57526. };
  57527. /**
  57528. * Copy the position of the bone to a vector3 in local or world space.
  57529. * @param space The space that the returned position is in.
  57530. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57531. * @param result The vector3 to copy the position to.
  57532. */
  57533. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  57534. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57535. if (space == BABYLON.Space.LOCAL) {
  57536. var lm = this.getLocalMatrix();
  57537. result.x = lm.m[12];
  57538. result.y = lm.m[13];
  57539. result.z = lm.m[14];
  57540. }
  57541. else {
  57542. var wm;
  57543. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57544. if (mesh) {
  57545. wm = mesh.getWorldMatrix();
  57546. }
  57547. this._skeleton.computeAbsoluteTransforms();
  57548. var tmat = Bone._tmpMats[0];
  57549. if (mesh) {
  57550. tmat.copyFrom(this.getAbsoluteTransform());
  57551. tmat.multiplyToRef(wm, tmat);
  57552. }
  57553. else {
  57554. tmat = this.getAbsoluteTransform();
  57555. }
  57556. result.x = tmat.m[12];
  57557. result.y = tmat.m[13];
  57558. result.z = tmat.m[14];
  57559. }
  57560. };
  57561. /**
  57562. * Get the absolute position of the bone (world space).
  57563. * @param mesh The mesh that this bone is attached to.
  57564. * @returns The absolute position of the bone
  57565. */
  57566. Bone.prototype.getAbsolutePosition = function (mesh) {
  57567. var pos = BABYLON.Vector3.Zero();
  57568. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  57569. return pos;
  57570. };
  57571. /**
  57572. * Copy the absolute position of the bone (world space) to the result param.
  57573. * @param mesh The mesh that this bone is attached to.
  57574. * @param result The vector3 to copy the absolute position to.
  57575. */
  57576. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  57577. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  57578. };
  57579. /**
  57580. * Compute the absolute transforms of this bone and its children.
  57581. */
  57582. Bone.prototype.computeAbsoluteTransforms = function () {
  57583. if (this._parent) {
  57584. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  57585. }
  57586. else {
  57587. this._absoluteTransform.copyFrom(this._localMatrix);
  57588. var poseMatrix = this._skeleton.getPoseMatrix();
  57589. if (poseMatrix) {
  57590. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  57591. }
  57592. }
  57593. var children = this.children;
  57594. var len = children.length;
  57595. for (var i = 0; i < len; i++) {
  57596. children[i].computeAbsoluteTransforms();
  57597. }
  57598. };
  57599. Bone.prototype._syncScaleVector = function () {
  57600. var lm = this.getLocalMatrix();
  57601. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  57602. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  57603. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  57604. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  57605. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  57606. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  57607. this._scaleVector.x = xs * Math.sqrt(xsq);
  57608. this._scaleVector.y = ys * Math.sqrt(ysq);
  57609. this._scaleVector.z = zs * Math.sqrt(zsq);
  57610. if (this._parent) {
  57611. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  57612. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  57613. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  57614. }
  57615. 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);
  57616. };
  57617. /**
  57618. * Get the world direction from an axis that is in the local space of the bone.
  57619. * @param localAxis The local direction that is used to compute the world direction.
  57620. * @param mesh The mesh that this bone is attached to.
  57621. * @returns The world direction
  57622. */
  57623. Bone.prototype.getDirection = function (localAxis, mesh) {
  57624. var result = BABYLON.Vector3.Zero();
  57625. this.getDirectionToRef(localAxis, mesh, result);
  57626. return result;
  57627. };
  57628. /**
  57629. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  57630. * @param localAxis The local direction that is used to compute the world direction.
  57631. * @param mesh The mesh that this bone is attached to.
  57632. * @param result The vector3 that the world direction will be copied to.
  57633. */
  57634. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  57635. var wm;
  57636. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57637. if (mesh) {
  57638. wm = mesh.getWorldMatrix();
  57639. }
  57640. this._skeleton.computeAbsoluteTransforms();
  57641. var mat = Bone._tmpMats[0];
  57642. mat.copyFrom(this.getAbsoluteTransform());
  57643. if (mesh) {
  57644. mat.multiplyToRef(wm, mat);
  57645. }
  57646. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  57647. result.normalize();
  57648. };
  57649. /**
  57650. * Get the euler rotation of the bone in local or world space.
  57651. * @param space The space that the rotation should be in.
  57652. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57653. * @returns The euler rotation
  57654. */
  57655. Bone.prototype.getRotation = function (space, mesh) {
  57656. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57657. var result = BABYLON.Vector3.Zero();
  57658. this.getRotationToRef(space, mesh, result);
  57659. return result;
  57660. };
  57661. /**
  57662. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  57663. * @param space The space that the rotation should be in.
  57664. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57665. * @param result The vector3 that the rotation should be copied to.
  57666. */
  57667. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  57668. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57669. var quat = Bone._tmpQuat;
  57670. this.getRotationQuaternionToRef(space, mesh, quat);
  57671. quat.toEulerAnglesToRef(result);
  57672. };
  57673. /**
  57674. * Get the quaternion rotation of the bone in either local or world space.
  57675. * @param space The space that the rotation should be in.
  57676. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57677. * @returns The quaternion rotation
  57678. */
  57679. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  57680. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57681. var result = BABYLON.Quaternion.Identity();
  57682. this.getRotationQuaternionToRef(space, mesh, result);
  57683. return result;
  57684. };
  57685. /**
  57686. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  57687. * @param space The space that the rotation should be in.
  57688. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57689. * @param result The quaternion that the rotation should be copied to.
  57690. */
  57691. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  57692. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57693. if (space == BABYLON.Space.LOCAL) {
  57694. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  57695. }
  57696. else {
  57697. var mat = Bone._tmpMats[0];
  57698. var amat = this.getAbsoluteTransform();
  57699. if (mesh) {
  57700. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  57701. }
  57702. else {
  57703. mat.copyFrom(amat);
  57704. }
  57705. mat.m[0] *= this._scalingDeterminant;
  57706. mat.m[1] *= this._scalingDeterminant;
  57707. mat.m[2] *= this._scalingDeterminant;
  57708. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  57709. }
  57710. };
  57711. /**
  57712. * Get the rotation matrix of the bone in local or world space.
  57713. * @param space The space that the rotation should be in.
  57714. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57715. * @returns The rotation matrix
  57716. */
  57717. Bone.prototype.getRotationMatrix = function (space, mesh) {
  57718. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57719. var result = BABYLON.Matrix.Identity();
  57720. this.getRotationMatrixToRef(space, mesh, result);
  57721. return result;
  57722. };
  57723. /**
  57724. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  57725. * @param space The space that the rotation should be in.
  57726. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57727. * @param result The quaternion that the rotation should be copied to.
  57728. */
  57729. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  57730. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57731. if (space == BABYLON.Space.LOCAL) {
  57732. this.getLocalMatrix().getRotationMatrixToRef(result);
  57733. }
  57734. else {
  57735. var mat = Bone._tmpMats[0];
  57736. var amat = this.getAbsoluteTransform();
  57737. if (mesh) {
  57738. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  57739. }
  57740. else {
  57741. mat.copyFrom(amat);
  57742. }
  57743. mat.m[0] *= this._scalingDeterminant;
  57744. mat.m[1] *= this._scalingDeterminant;
  57745. mat.m[2] *= this._scalingDeterminant;
  57746. mat.getRotationMatrixToRef(result);
  57747. }
  57748. };
  57749. /**
  57750. * Get the world position of a point that is in the local space of the bone.
  57751. * @param position The local position
  57752. * @param mesh The mesh that this bone is attached to.
  57753. * @returns The world position
  57754. */
  57755. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  57756. var result = BABYLON.Vector3.Zero();
  57757. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  57758. return result;
  57759. };
  57760. /**
  57761. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  57762. * @param position The local position
  57763. * @param mesh The mesh that this bone is attached to.
  57764. * @param result The vector3 that the world position should be copied to.
  57765. */
  57766. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  57767. var wm;
  57768. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57769. if (mesh) {
  57770. wm = mesh.getWorldMatrix();
  57771. }
  57772. this._skeleton.computeAbsoluteTransforms();
  57773. var tmat = Bone._tmpMats[0];
  57774. if (mesh) {
  57775. tmat.copyFrom(this.getAbsoluteTransform());
  57776. tmat.multiplyToRef(wm, tmat);
  57777. }
  57778. else {
  57779. tmat = this.getAbsoluteTransform();
  57780. }
  57781. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  57782. };
  57783. /**
  57784. * Get the local position of a point that is in world space.
  57785. * @param position The world position
  57786. * @param mesh The mesh that this bone is attached to.
  57787. * @returns The local position
  57788. */
  57789. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  57790. var result = BABYLON.Vector3.Zero();
  57791. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  57792. return result;
  57793. };
  57794. /**
  57795. * Get the local position of a point that is in world space and copy it to the result param.
  57796. * @param position The world position
  57797. * @param mesh The mesh that this bone is attached to.
  57798. * @param result The vector3 that the local position should be copied to.
  57799. */
  57800. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  57801. var wm;
  57802. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57803. if (mesh) {
  57804. wm = mesh.getWorldMatrix();
  57805. }
  57806. this._skeleton.computeAbsoluteTransforms();
  57807. var tmat = Bone._tmpMats[0];
  57808. tmat.copyFrom(this.getAbsoluteTransform());
  57809. if (mesh) {
  57810. tmat.multiplyToRef(wm, tmat);
  57811. }
  57812. tmat.invert();
  57813. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  57814. };
  57815. return Bone;
  57816. }(BABYLON.Node));
  57817. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57818. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  57819. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  57820. BABYLON.Bone = Bone;
  57821. })(BABYLON || (BABYLON = {}));
  57822. //# sourceMappingURL=babylon.bone.js.map
  57823. var BABYLON;
  57824. (function (BABYLON) {
  57825. var BoneIKController = (function () {
  57826. function BoneIKController(mesh, bone, options) {
  57827. this.targetPosition = BABYLON.Vector3.Zero();
  57828. this.poleTargetPosition = BABYLON.Vector3.Zero();
  57829. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  57830. this.poleAngle = 0;
  57831. this.slerpAmount = 1;
  57832. this._bone1Quat = BABYLON.Quaternion.Identity();
  57833. this._bone1Mat = BABYLON.Matrix.Identity();
  57834. this._bone2Ang = Math.PI;
  57835. this._maxAngle = Math.PI;
  57836. this._rightHandedSystem = false;
  57837. this._bendAxis = BABYLON.Vector3.Right();
  57838. this._slerping = false;
  57839. this._adjustRoll = 0;
  57840. this._bone2 = bone;
  57841. this._bone1 = bone.getParent();
  57842. this.mesh = mesh;
  57843. var bonePos = bone.getPosition();
  57844. if (bone.getAbsoluteTransform().determinant() > 0) {
  57845. this._rightHandedSystem = true;
  57846. this._bendAxis.x = 0;
  57847. this._bendAxis.y = 0;
  57848. this._bendAxis.z = -1;
  57849. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  57850. this._adjustRoll = Math.PI * .5;
  57851. this._bendAxis.z = 1;
  57852. }
  57853. }
  57854. if (this._bone1.length) {
  57855. var boneScale1 = this._bone1.getScale();
  57856. var boneScale2 = this._bone2.getScale();
  57857. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  57858. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  57859. }
  57860. else if (this._bone1.children[0]) {
  57861. mesh.computeWorldMatrix(true);
  57862. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  57863. var pos2 = this._bone2.getAbsolutePosition(mesh);
  57864. var pos3 = this._bone1.getAbsolutePosition(mesh);
  57865. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  57866. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  57867. }
  57868. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  57869. this.maxAngle = Math.PI;
  57870. if (options) {
  57871. if (options.targetMesh) {
  57872. this.targetMesh = options.targetMesh;
  57873. this.targetMesh.computeWorldMatrix(true);
  57874. }
  57875. if (options.poleTargetMesh) {
  57876. this.poleTargetMesh = options.poleTargetMesh;
  57877. this.poleTargetMesh.computeWorldMatrix(true);
  57878. }
  57879. else if (options.poleTargetBone) {
  57880. this.poleTargetBone = options.poleTargetBone;
  57881. }
  57882. else if (this._bone1.getParent()) {
  57883. this.poleTargetBone = this._bone1.getParent();
  57884. }
  57885. if (options.poleTargetLocalOffset) {
  57886. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  57887. }
  57888. if (options.poleAngle) {
  57889. this.poleAngle = options.poleAngle;
  57890. }
  57891. if (options.bendAxis) {
  57892. this._bendAxis.copyFrom(options.bendAxis);
  57893. }
  57894. if (options.maxAngle) {
  57895. this.maxAngle = options.maxAngle;
  57896. }
  57897. if (options.slerpAmount) {
  57898. this.slerpAmount = options.slerpAmount;
  57899. }
  57900. }
  57901. }
  57902. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  57903. get: function () {
  57904. return this._maxAngle;
  57905. },
  57906. set: function (value) {
  57907. this._setMaxAngle(value);
  57908. },
  57909. enumerable: true,
  57910. configurable: true
  57911. });
  57912. BoneIKController.prototype._setMaxAngle = function (ang) {
  57913. if (ang < 0) {
  57914. ang = 0;
  57915. }
  57916. if (ang > Math.PI || ang == undefined) {
  57917. ang = Math.PI;
  57918. }
  57919. this._maxAngle = ang;
  57920. var a = this._bone1Length;
  57921. var b = this._bone2Length;
  57922. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  57923. };
  57924. BoneIKController.prototype.update = function () {
  57925. var bone1 = this._bone1;
  57926. var target = this.targetPosition;
  57927. var poleTarget = this.poleTargetPosition;
  57928. var mat1 = BoneIKController._tmpMats[0];
  57929. var mat2 = BoneIKController._tmpMats[1];
  57930. if (this.targetMesh) {
  57931. target.copyFrom(this.targetMesh.getAbsolutePosition());
  57932. }
  57933. if (this.poleTargetBone) {
  57934. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  57935. }
  57936. else if (this.poleTargetMesh) {
  57937. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  57938. }
  57939. var bonePos = BoneIKController._tmpVecs[0];
  57940. var zaxis = BoneIKController._tmpVecs[1];
  57941. var xaxis = BoneIKController._tmpVecs[2];
  57942. var yaxis = BoneIKController._tmpVecs[3];
  57943. var upAxis = BoneIKController._tmpVecs[4];
  57944. var _tmpQuat = BoneIKController._tmpQuat;
  57945. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  57946. poleTarget.subtractToRef(bonePos, upAxis);
  57947. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  57948. upAxis.y = 1;
  57949. }
  57950. else {
  57951. upAxis.normalize();
  57952. }
  57953. target.subtractToRef(bonePos, yaxis);
  57954. yaxis.normalize();
  57955. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  57956. zaxis.normalize();
  57957. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  57958. xaxis.normalize();
  57959. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  57960. var a = this._bone1Length;
  57961. var b = this._bone2Length;
  57962. var c = BABYLON.Vector3.Distance(bonePos, target);
  57963. if (this._maxReach > 0) {
  57964. c = Math.min(this._maxReach, c);
  57965. }
  57966. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  57967. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  57968. if (acosa > 1) {
  57969. acosa = 1;
  57970. }
  57971. if (acosb > 1) {
  57972. acosb = 1;
  57973. }
  57974. if (acosa < -1) {
  57975. acosa = -1;
  57976. }
  57977. if (acosb < -1) {
  57978. acosb = -1;
  57979. }
  57980. var angA = Math.acos(acosa);
  57981. var angB = Math.acos(acosb);
  57982. var angC = -angA - angB;
  57983. if (this._rightHandedSystem) {
  57984. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  57985. mat2.multiplyToRef(mat1, mat1);
  57986. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  57987. mat2.multiplyToRef(mat1, mat1);
  57988. }
  57989. else {
  57990. var _tmpVec = BoneIKController._tmpVecs[5];
  57991. _tmpVec.copyFrom(this._bendAxis);
  57992. _tmpVec.x *= -1;
  57993. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  57994. mat2.multiplyToRef(mat1, mat1);
  57995. }
  57996. if (this.poleAngle) {
  57997. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  57998. mat1.multiplyToRef(mat2, mat1);
  57999. }
  58000. if (this.slerpAmount < 1) {
  58001. if (!this._slerping) {
  58002. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  58003. }
  58004. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  58005. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  58006. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  58007. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  58008. this._slerping = true;
  58009. }
  58010. else {
  58011. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  58012. this._bone1Mat.copyFrom(mat1);
  58013. this._slerping = false;
  58014. }
  58015. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  58016. this._bone2Ang = angC;
  58017. };
  58018. return BoneIKController;
  58019. }());
  58020. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58021. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  58022. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  58023. BABYLON.BoneIKController = BoneIKController;
  58024. })(BABYLON || (BABYLON = {}));
  58025. //# sourceMappingURL=babylon.boneIKController.js.map
  58026. var BABYLON;
  58027. (function (BABYLON) {
  58028. var BoneLookController = (function () {
  58029. /**
  58030. * Create a BoneLookController
  58031. * @param mesh the mesh that the bone belongs to
  58032. * @param bone the bone that will be looking to the target
  58033. * @param target the target Vector3 to look at
  58034. * @param settings optional settings:
  58035. * - maxYaw: the maximum angle the bone will yaw to
  58036. * - minYaw: the minimum angle the bone will yaw to
  58037. * - maxPitch: the maximum angle the bone will pitch to
  58038. * - minPitch: the minimum angle the bone will yaw to
  58039. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  58040. * - upAxis: the up axis of the coordinate system
  58041. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  58042. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  58043. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  58044. * - adjustYaw: used to make an adjustment to the yaw of the bone
  58045. * - adjustPitch: used to make an adjustment to the pitch of the bone
  58046. * - adjustRoll: used to make an adjustment to the roll of the bone
  58047. **/
  58048. function BoneLookController(mesh, bone, target, options) {
  58049. /**
  58050. * The up axis of the coordinate system that is used when the bone is rotated.
  58051. */
  58052. this.upAxis = BABYLON.Vector3.Up();
  58053. /**
  58054. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  58055. */
  58056. this.upAxisSpace = BABYLON.Space.LOCAL;
  58057. /**
  58058. * Used to make an adjustment to the yaw of the bone.
  58059. */
  58060. this.adjustYaw = 0;
  58061. /**
  58062. * Used to make an adjustment to the pitch of the bone.
  58063. */
  58064. this.adjustPitch = 0;
  58065. /**
  58066. * Used to make an adjustment to the roll of the bone.
  58067. */
  58068. this.adjustRoll = 0;
  58069. /**
  58070. * 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).
  58071. */
  58072. this.slerpAmount = 1;
  58073. this._boneQuat = BABYLON.Quaternion.Identity();
  58074. this._slerping = false;
  58075. this._firstFrameSkipped = false;
  58076. this._fowardAxis = BABYLON.Vector3.Forward();
  58077. this.mesh = mesh;
  58078. this.bone = bone;
  58079. this.target = target;
  58080. if (options) {
  58081. if (options.adjustYaw) {
  58082. this.adjustYaw = options.adjustYaw;
  58083. }
  58084. if (options.adjustPitch) {
  58085. this.adjustPitch = options.adjustPitch;
  58086. }
  58087. if (options.adjustRoll) {
  58088. this.adjustRoll = options.adjustRoll;
  58089. }
  58090. if (options.maxYaw != null) {
  58091. this.maxYaw = options.maxYaw;
  58092. }
  58093. else {
  58094. this.maxYaw = Math.PI;
  58095. }
  58096. if (options.minYaw != null) {
  58097. this.minYaw = options.minYaw;
  58098. }
  58099. else {
  58100. this.minYaw = -Math.PI;
  58101. }
  58102. if (options.maxPitch != null) {
  58103. this.maxPitch = options.maxPitch;
  58104. }
  58105. else {
  58106. this.maxPitch = Math.PI;
  58107. }
  58108. if (options.minPitch != null) {
  58109. this.minPitch = options.minPitch;
  58110. }
  58111. else {
  58112. this.minPitch = -Math.PI;
  58113. }
  58114. if (options.slerpAmount != null) {
  58115. this.slerpAmount = options.slerpAmount;
  58116. }
  58117. if (options.upAxis != null) {
  58118. this.upAxis = options.upAxis;
  58119. }
  58120. if (options.upAxisSpace != null) {
  58121. this.upAxisSpace = options.upAxisSpace;
  58122. }
  58123. if (options.yawAxis != null || options.pitchAxis != null) {
  58124. var newYawAxis = BABYLON.Axis.Y;
  58125. var newPitchAxis = BABYLON.Axis.X;
  58126. if (options.yawAxis != null) {
  58127. newYawAxis = options.yawAxis.clone();
  58128. newYawAxis.normalize();
  58129. }
  58130. if (options.pitchAxis != null) {
  58131. newPitchAxis = options.pitchAxis.clone();
  58132. newPitchAxis.normalize();
  58133. }
  58134. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  58135. this._transformYawPitch = BABYLON.Matrix.Identity();
  58136. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  58137. this._transformYawPitchInv = this._transformYawPitch.clone();
  58138. this._transformYawPitch.invert();
  58139. }
  58140. }
  58141. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  58142. this.upAxisSpace = BABYLON.Space.LOCAL;
  58143. }
  58144. }
  58145. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  58146. /**
  58147. * Get/set the minimum yaw angle that the bone can look to.
  58148. */
  58149. get: function () {
  58150. return this._minYaw;
  58151. },
  58152. set: function (value) {
  58153. this._minYaw = value;
  58154. this._minYawSin = Math.sin(value);
  58155. this._minYawCos = Math.cos(value);
  58156. if (this._maxYaw != null) {
  58157. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  58158. this._yawRange = this._maxYaw - this._minYaw;
  58159. }
  58160. },
  58161. enumerable: true,
  58162. configurable: true
  58163. });
  58164. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  58165. /**
  58166. * Get/set the maximum yaw angle that the bone can look to.
  58167. */
  58168. get: function () {
  58169. return this._maxYaw;
  58170. },
  58171. set: function (value) {
  58172. this._maxYaw = value;
  58173. this._maxYawSin = Math.sin(value);
  58174. this._maxYawCos = Math.cos(value);
  58175. if (this._minYaw != null) {
  58176. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  58177. this._yawRange = this._maxYaw - this._minYaw;
  58178. }
  58179. },
  58180. enumerable: true,
  58181. configurable: true
  58182. });
  58183. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  58184. /**
  58185. * Get/set the minimum pitch angle that the bone can look to.
  58186. */
  58187. get: function () {
  58188. return this._minPitch;
  58189. },
  58190. set: function (value) {
  58191. this._minPitch = value;
  58192. this._minPitchTan = Math.tan(value);
  58193. },
  58194. enumerable: true,
  58195. configurable: true
  58196. });
  58197. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  58198. /**
  58199. * Get/set the maximum pitch angle that the bone can look to.
  58200. */
  58201. get: function () {
  58202. return this._maxPitch;
  58203. },
  58204. set: function (value) {
  58205. this._maxPitch = value;
  58206. this._maxPitchTan = Math.tan(value);
  58207. },
  58208. enumerable: true,
  58209. configurable: true
  58210. });
  58211. /**
  58212. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  58213. */
  58214. BoneLookController.prototype.update = function () {
  58215. //skip the first frame when slerping so that the mesh rotation is correct
  58216. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  58217. this._firstFrameSkipped = true;
  58218. return;
  58219. }
  58220. var bone = this.bone;
  58221. var bonePos = BoneLookController._tmpVecs[0];
  58222. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  58223. var target = this.target;
  58224. var _tmpMat1 = BoneLookController._tmpMats[0];
  58225. var _tmpMat2 = BoneLookController._tmpMats[1];
  58226. var mesh = this.mesh;
  58227. var parentBone = bone.getParent();
  58228. var upAxis = BoneLookController._tmpVecs[1];
  58229. upAxis.copyFrom(this.upAxis);
  58230. if (this.upAxisSpace == BABYLON.Space.BONE) {
  58231. if (this._transformYawPitch) {
  58232. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  58233. }
  58234. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  58235. }
  58236. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  58237. mesh.getDirectionToRef(upAxis, upAxis);
  58238. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  58239. upAxis.normalize();
  58240. }
  58241. }
  58242. var checkYaw = false;
  58243. var checkPitch = false;
  58244. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  58245. checkYaw = true;
  58246. }
  58247. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  58248. checkPitch = true;
  58249. }
  58250. if (checkYaw || checkPitch) {
  58251. var spaceMat = BoneLookController._tmpMats[2];
  58252. var spaceMatInv = BoneLookController._tmpMats[3];
  58253. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  58254. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  58255. }
  58256. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  58257. spaceMat.copyFrom(mesh.getWorldMatrix());
  58258. }
  58259. else {
  58260. var forwardAxis = BoneLookController._tmpVecs[2];
  58261. forwardAxis.copyFrom(this._fowardAxis);
  58262. if (this._transformYawPitch) {
  58263. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  58264. }
  58265. if (parentBone) {
  58266. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  58267. }
  58268. else {
  58269. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  58270. }
  58271. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  58272. rightAxis.normalize();
  58273. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  58274. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  58275. }
  58276. spaceMat.invertToRef(spaceMatInv);
  58277. var xzlen;
  58278. if (checkPitch) {
  58279. var localTarget = BoneLookController._tmpVecs[3];
  58280. target.subtractToRef(bonePos, localTarget);
  58281. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  58282. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  58283. var pitch = Math.atan2(localTarget.y, xzlen);
  58284. var newPitch = pitch;
  58285. if (pitch > this._maxPitch) {
  58286. localTarget.y = this._maxPitchTan * xzlen;
  58287. newPitch = this._maxPitch;
  58288. }
  58289. else if (pitch < this._minPitch) {
  58290. localTarget.y = this._minPitchTan * xzlen;
  58291. newPitch = this._minPitch;
  58292. }
  58293. if (pitch != newPitch) {
  58294. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  58295. localTarget.addInPlace(bonePos);
  58296. target = localTarget;
  58297. }
  58298. }
  58299. if (checkYaw) {
  58300. var localTarget = BoneLookController._tmpVecs[4];
  58301. target.subtractToRef(bonePos, localTarget);
  58302. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  58303. var yaw = Math.atan2(localTarget.x, localTarget.z);
  58304. var newYaw = yaw;
  58305. if (yaw > this._maxYaw || yaw < this._minYaw) {
  58306. if (xzlen == null) {
  58307. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  58308. }
  58309. if (this._yawRange > Math.PI) {
  58310. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  58311. localTarget.z = this._maxYawCos * xzlen;
  58312. localTarget.x = this._maxYawSin * xzlen;
  58313. newYaw = this._maxYaw;
  58314. }
  58315. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  58316. localTarget.z = this._minYawCos * xzlen;
  58317. localTarget.x = this._minYawSin * xzlen;
  58318. newYaw = this._minYaw;
  58319. }
  58320. }
  58321. else {
  58322. if (yaw > this._maxYaw) {
  58323. localTarget.z = this._maxYawCos * xzlen;
  58324. localTarget.x = this._maxYawSin * xzlen;
  58325. newYaw = this._maxYaw;
  58326. }
  58327. else if (yaw < this._minYaw) {
  58328. localTarget.z = this._minYawCos * xzlen;
  58329. localTarget.x = this._minYawSin * xzlen;
  58330. newYaw = this._minYaw;
  58331. }
  58332. }
  58333. }
  58334. if (this._slerping && this._yawRange > Math.PI) {
  58335. //are we going to be crossing into the min/max region?
  58336. var boneFwd = BoneLookController._tmpVecs[8];
  58337. boneFwd.copyFrom(BABYLON.Axis.Z);
  58338. if (this._transformYawPitch) {
  58339. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  58340. }
  58341. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  58342. this._boneQuat.toRotationMatrix(boneRotMat);
  58343. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  58344. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  58345. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  58346. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  58347. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  58348. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  58349. if (angBtwTar > angBtwMidYaw) {
  58350. if (xzlen == null) {
  58351. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  58352. }
  58353. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  58354. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  58355. if (angBtwMin < angBtwMax) {
  58356. newYaw = boneYaw + Math.PI * .75;
  58357. localTarget.z = Math.cos(newYaw) * xzlen;
  58358. localTarget.x = Math.sin(newYaw) * xzlen;
  58359. }
  58360. else {
  58361. newYaw = boneYaw - Math.PI * .75;
  58362. localTarget.z = Math.cos(newYaw) * xzlen;
  58363. localTarget.x = Math.sin(newYaw) * xzlen;
  58364. }
  58365. }
  58366. }
  58367. if (yaw != newYaw) {
  58368. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  58369. localTarget.addInPlace(bonePos);
  58370. target = localTarget;
  58371. }
  58372. }
  58373. }
  58374. var zaxis = BoneLookController._tmpVecs[5];
  58375. var xaxis = BoneLookController._tmpVecs[6];
  58376. var yaxis = BoneLookController._tmpVecs[7];
  58377. var _tmpQuat = BoneLookController._tmpQuat;
  58378. target.subtractToRef(bonePos, zaxis);
  58379. zaxis.normalize();
  58380. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  58381. xaxis.normalize();
  58382. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  58383. yaxis.normalize();
  58384. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  58385. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  58386. return;
  58387. }
  58388. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  58389. return;
  58390. }
  58391. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  58392. return;
  58393. }
  58394. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  58395. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  58396. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  58397. }
  58398. if (this.slerpAmount < 1) {
  58399. if (!this._slerping) {
  58400. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  58401. }
  58402. if (this._transformYawPitch) {
  58403. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  58404. }
  58405. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  58406. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  58407. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  58408. this._slerping = true;
  58409. }
  58410. else {
  58411. if (this._transformYawPitch) {
  58412. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  58413. }
  58414. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  58415. this._slerping = false;
  58416. }
  58417. };
  58418. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  58419. var angDiff = ang2 - ang1;
  58420. angDiff %= Math.PI * 2;
  58421. if (angDiff > Math.PI) {
  58422. angDiff -= Math.PI * 2;
  58423. }
  58424. else if (angDiff < -Math.PI) {
  58425. angDiff += Math.PI * 2;
  58426. }
  58427. return angDiff;
  58428. };
  58429. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  58430. ang1 %= (2 * Math.PI);
  58431. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  58432. ang2 %= (2 * Math.PI);
  58433. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  58434. var ab = 0;
  58435. if (ang1 < ang2) {
  58436. ab = ang2 - ang1;
  58437. }
  58438. else {
  58439. ab = ang1 - ang2;
  58440. }
  58441. if (ab > Math.PI) {
  58442. ab = Math.PI * 2 - ab;
  58443. }
  58444. return ab;
  58445. };
  58446. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  58447. ang %= (2 * Math.PI);
  58448. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  58449. ang1 %= (2 * Math.PI);
  58450. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  58451. ang2 %= (2 * Math.PI);
  58452. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  58453. if (ang1 < ang2) {
  58454. if (ang > ang1 && ang < ang2) {
  58455. return true;
  58456. }
  58457. }
  58458. else {
  58459. if (ang > ang2 && ang < ang1) {
  58460. return true;
  58461. }
  58462. }
  58463. return false;
  58464. };
  58465. return BoneLookController;
  58466. }());
  58467. 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()];
  58468. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  58469. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  58470. BABYLON.BoneLookController = BoneLookController;
  58471. })(BABYLON || (BABYLON = {}));
  58472. //# sourceMappingURL=babylon.boneLookController.js.map
  58473. var BABYLON;
  58474. (function (BABYLON) {
  58475. var Skeleton = (function () {
  58476. function Skeleton(name, id, scene) {
  58477. this.name = name;
  58478. this.id = id;
  58479. this.bones = new Array();
  58480. this.needInitialSkinMatrix = false;
  58481. this._isDirty = true;
  58482. this._meshesWithPoseMatrix = new Array();
  58483. this._identity = BABYLON.Matrix.Identity();
  58484. this._ranges = {};
  58485. this._lastAbsoluteTransformsUpdateId = -1;
  58486. // Events
  58487. /**
  58488. * An event triggered before computing the skeleton's matrices
  58489. * @type {BABYLON.Observable}
  58490. */
  58491. this.onBeforeComputeObservable = new BABYLON.Observable();
  58492. this.bones = [];
  58493. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58494. scene.skeletons.push(this);
  58495. //make sure it will recalculate the matrix next time prepare is called.
  58496. this._isDirty = true;
  58497. }
  58498. // Members
  58499. Skeleton.prototype.getTransformMatrices = function (mesh) {
  58500. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  58501. return mesh._bonesTransformMatrices;
  58502. }
  58503. if (!this._transformMatrices) {
  58504. this.prepare();
  58505. }
  58506. return this._transformMatrices;
  58507. };
  58508. Skeleton.prototype.getScene = function () {
  58509. return this._scene;
  58510. };
  58511. // Methods
  58512. /**
  58513. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  58514. */
  58515. Skeleton.prototype.toString = function (fullDetails) {
  58516. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  58517. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  58518. if (fullDetails) {
  58519. ret += ", Ranges: {";
  58520. var first = true;
  58521. for (var name_1 in this._ranges) {
  58522. if (first) {
  58523. ret += ", ";
  58524. first = false;
  58525. }
  58526. ret += name_1;
  58527. }
  58528. ret += "}";
  58529. }
  58530. return ret;
  58531. };
  58532. /**
  58533. * Get bone's index searching by name
  58534. * @param {string} name is bone's name to search for
  58535. * @return {number} Indice of the bone. Returns -1 if not found
  58536. */
  58537. Skeleton.prototype.getBoneIndexByName = function (name) {
  58538. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  58539. if (this.bones[boneIndex].name === name) {
  58540. return boneIndex;
  58541. }
  58542. }
  58543. return -1;
  58544. };
  58545. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  58546. // check name not already in use
  58547. if (!this._ranges[name]) {
  58548. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  58549. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  58550. if (this.bones[i].animations[0]) {
  58551. this.bones[i].animations[0].createRange(name, from, to);
  58552. }
  58553. }
  58554. }
  58555. };
  58556. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  58557. if (deleteFrames === void 0) { deleteFrames = true; }
  58558. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  58559. if (this.bones[i].animations[0]) {
  58560. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  58561. }
  58562. }
  58563. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  58564. };
  58565. Skeleton.prototype.getAnimationRange = function (name) {
  58566. return this._ranges[name];
  58567. };
  58568. /**
  58569. * Returns as an Array, all AnimationRanges defined on this skeleton
  58570. */
  58571. Skeleton.prototype.getAnimationRanges = function () {
  58572. var animationRanges = [];
  58573. var name;
  58574. var i = 0;
  58575. for (name in this._ranges) {
  58576. animationRanges[i] = this._ranges[name];
  58577. i++;
  58578. }
  58579. return animationRanges;
  58580. };
  58581. /**
  58582. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  58583. */
  58584. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  58585. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  58586. if (this._ranges[name] || !source.getAnimationRange(name)) {
  58587. return false;
  58588. }
  58589. var ret = true;
  58590. var frameOffset = this._getHighestAnimationFrame() + 1;
  58591. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  58592. var boneDict = {};
  58593. var sourceBones = source.bones;
  58594. var nBones;
  58595. var i;
  58596. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  58597. boneDict[sourceBones[i].name] = sourceBones[i];
  58598. }
  58599. if (this.bones.length !== sourceBones.length) {
  58600. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  58601. ret = false;
  58602. }
  58603. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  58604. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  58605. var boneName = this.bones[i].name;
  58606. var sourceBone = boneDict[boneName];
  58607. if (sourceBone) {
  58608. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  58609. }
  58610. else {
  58611. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  58612. ret = false;
  58613. }
  58614. }
  58615. // do not call createAnimationRange(), since it also is done to bones, which was already done
  58616. var range = source.getAnimationRange(name);
  58617. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  58618. return ret;
  58619. };
  58620. Skeleton.prototype.returnToRest = function () {
  58621. for (var index = 0; index < this.bones.length; index++) {
  58622. this.bones[index].returnToRest();
  58623. }
  58624. };
  58625. Skeleton.prototype._getHighestAnimationFrame = function () {
  58626. var ret = 0;
  58627. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  58628. if (this.bones[i].animations[0]) {
  58629. var highest = this.bones[i].animations[0].getHighestFrame();
  58630. if (ret < highest) {
  58631. ret = highest;
  58632. }
  58633. }
  58634. }
  58635. return ret;
  58636. };
  58637. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  58638. var range = this.getAnimationRange(name);
  58639. if (!range) {
  58640. return null;
  58641. }
  58642. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  58643. };
  58644. Skeleton.prototype._markAsDirty = function () {
  58645. this._isDirty = true;
  58646. };
  58647. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  58648. this._meshesWithPoseMatrix.push(mesh);
  58649. };
  58650. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  58651. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  58652. if (index > -1) {
  58653. this._meshesWithPoseMatrix.splice(index, 1);
  58654. }
  58655. };
  58656. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  58657. this.onBeforeComputeObservable.notifyObservers(this);
  58658. for (var index = 0; index < this.bones.length; index++) {
  58659. var bone = this.bones[index];
  58660. var parentBone = bone.getParent();
  58661. if (parentBone) {
  58662. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  58663. }
  58664. else {
  58665. if (initialSkinMatrix) {
  58666. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  58667. }
  58668. else {
  58669. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  58670. }
  58671. }
  58672. if (bone._index !== -1) {
  58673. var mappedIndex = bone._index === undefined ? index : bone._index;
  58674. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  58675. }
  58676. }
  58677. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  58678. };
  58679. Skeleton.prototype.prepare = function () {
  58680. if (!this._isDirty) {
  58681. return;
  58682. }
  58683. if (this.needInitialSkinMatrix) {
  58684. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  58685. var mesh = this._meshesWithPoseMatrix[index];
  58686. var poseMatrix = mesh.getPoseMatrix();
  58687. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  58688. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  58689. }
  58690. if (this._synchronizedWithMesh !== mesh) {
  58691. this._synchronizedWithMesh = mesh;
  58692. // Prepare bones
  58693. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  58694. var bone = this.bones[boneIndex];
  58695. if (!bone.getParent()) {
  58696. var matrix = bone.getBaseMatrix();
  58697. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  58698. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  58699. }
  58700. }
  58701. }
  58702. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  58703. }
  58704. }
  58705. else {
  58706. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  58707. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  58708. }
  58709. this._computeTransformMatrices(this._transformMatrices, null);
  58710. }
  58711. this._isDirty = false;
  58712. this._scene._activeBones.addCount(this.bones.length, false);
  58713. };
  58714. Skeleton.prototype.getAnimatables = function () {
  58715. if (!this._animatables || this._animatables.length !== this.bones.length) {
  58716. this._animatables = [];
  58717. for (var index = 0; index < this.bones.length; index++) {
  58718. this._animatables.push(this.bones[index]);
  58719. }
  58720. }
  58721. return this._animatables;
  58722. };
  58723. Skeleton.prototype.clone = function (name, id) {
  58724. var result = new Skeleton(name, id || name, this._scene);
  58725. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  58726. for (var index = 0; index < this.bones.length; index++) {
  58727. var source = this.bones[index];
  58728. var parentBone = null;
  58729. if (source.getParent()) {
  58730. var parentIndex = this.bones.indexOf(source.getParent());
  58731. parentBone = result.bones[parentIndex];
  58732. }
  58733. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  58734. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  58735. }
  58736. if (this._ranges) {
  58737. result._ranges = {};
  58738. for (var rangeName in this._ranges) {
  58739. result._ranges[rangeName] = this._ranges[rangeName].clone();
  58740. }
  58741. }
  58742. this._isDirty = true;
  58743. return result;
  58744. };
  58745. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  58746. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  58747. this.bones.forEach(function (bone) {
  58748. bone.animations.forEach(function (animation) {
  58749. animation.enableBlending = true;
  58750. animation.blendingSpeed = blendingSpeed;
  58751. });
  58752. });
  58753. };
  58754. Skeleton.prototype.dispose = function () {
  58755. this._meshesWithPoseMatrix = [];
  58756. // Animations
  58757. this.getScene().stopAnimation(this);
  58758. // Remove from scene
  58759. this.getScene().removeSkeleton(this);
  58760. };
  58761. Skeleton.prototype.serialize = function () {
  58762. var serializationObject = {};
  58763. serializationObject.name = this.name;
  58764. serializationObject.id = this.id;
  58765. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  58766. serializationObject.bones = [];
  58767. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  58768. for (var index = 0; index < this.bones.length; index++) {
  58769. var bone = this.bones[index];
  58770. var serializedBone = {
  58771. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  58772. name: bone.name,
  58773. matrix: bone.getBaseMatrix().toArray(),
  58774. rest: bone.getRestPose().toArray()
  58775. };
  58776. serializationObject.bones.push(serializedBone);
  58777. if (bone.length) {
  58778. serializedBone.length = bone.length;
  58779. }
  58780. if (bone.animations && bone.animations.length > 0) {
  58781. serializedBone.animation = bone.animations[0].serialize();
  58782. }
  58783. serializationObject.ranges = [];
  58784. for (var name in this._ranges) {
  58785. var range = {};
  58786. range.name = name;
  58787. range.from = this._ranges[name].from;
  58788. range.to = this._ranges[name].to;
  58789. serializationObject.ranges.push(range);
  58790. }
  58791. }
  58792. return serializationObject;
  58793. };
  58794. Skeleton.Parse = function (parsedSkeleton, scene) {
  58795. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  58796. if (parsedSkeleton.dimensionsAtRest) {
  58797. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  58798. }
  58799. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  58800. var index;
  58801. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  58802. var parsedBone = parsedSkeleton.bones[index];
  58803. var parentBone = null;
  58804. if (parsedBone.parentBoneIndex > -1) {
  58805. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  58806. }
  58807. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  58808. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  58809. if (parsedBone.length) {
  58810. bone.length = parsedBone.length;
  58811. }
  58812. if (parsedBone.animation) {
  58813. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  58814. }
  58815. }
  58816. // placed after bones, so createAnimationRange can cascade down
  58817. if (parsedSkeleton.ranges) {
  58818. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  58819. var data = parsedSkeleton.ranges[index];
  58820. skeleton.createAnimationRange(data.name, data.from, data.to);
  58821. }
  58822. }
  58823. return skeleton;
  58824. };
  58825. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  58826. if (forceUpdate === void 0) { forceUpdate = false; }
  58827. var renderId = this._scene.getRenderId();
  58828. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  58829. this.bones[0].computeAbsoluteTransforms();
  58830. this._lastAbsoluteTransformsUpdateId = renderId;
  58831. }
  58832. };
  58833. Skeleton.prototype.getPoseMatrix = function () {
  58834. var poseMatrix;
  58835. if (this._meshesWithPoseMatrix.length > 0) {
  58836. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  58837. }
  58838. return poseMatrix;
  58839. };
  58840. Skeleton.prototype.sortBones = function () {
  58841. var bones = new Array();
  58842. var visited = new Array(this.bones.length);
  58843. for (var index = 0; index < this.bones.length; index++) {
  58844. this._sortBones(index, bones, visited);
  58845. }
  58846. this.bones = bones;
  58847. };
  58848. Skeleton.prototype._sortBones = function (index, bones, visited) {
  58849. if (visited[index]) {
  58850. return;
  58851. }
  58852. visited[index] = true;
  58853. var bone = this.bones[index];
  58854. if (bone._index === undefined) {
  58855. bone._index = index;
  58856. }
  58857. var parentBone = bone.getParent();
  58858. if (parentBone) {
  58859. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  58860. }
  58861. bones.push(bone);
  58862. };
  58863. return Skeleton;
  58864. }());
  58865. BABYLON.Skeleton = Skeleton;
  58866. })(BABYLON || (BABYLON = {}));
  58867. //# sourceMappingURL=babylon.skeleton.js.map
  58868. var BABYLON;
  58869. (function (BABYLON) {
  58870. var SphericalPolynomial = (function () {
  58871. function SphericalPolynomial() {
  58872. this.x = BABYLON.Vector3.Zero();
  58873. this.y = BABYLON.Vector3.Zero();
  58874. this.z = BABYLON.Vector3.Zero();
  58875. this.xx = BABYLON.Vector3.Zero();
  58876. this.yy = BABYLON.Vector3.Zero();
  58877. this.zz = BABYLON.Vector3.Zero();
  58878. this.xy = BABYLON.Vector3.Zero();
  58879. this.yz = BABYLON.Vector3.Zero();
  58880. this.zx = BABYLON.Vector3.Zero();
  58881. }
  58882. SphericalPolynomial.prototype.addAmbient = function (color) {
  58883. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  58884. this.xx = this.xx.add(colorVector);
  58885. this.yy = this.yy.add(colorVector);
  58886. this.zz = this.zz.add(colorVector);
  58887. };
  58888. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  58889. var result = new SphericalPolynomial();
  58890. result.x = harmonics.L11.scale(1.02333);
  58891. result.y = harmonics.L1_1.scale(1.02333);
  58892. result.z = harmonics.L10.scale(1.02333);
  58893. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  58894. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  58895. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  58896. result.yz = harmonics.L2_1.scale(0.858086);
  58897. result.zx = harmonics.L21.scale(0.858086);
  58898. result.xy = harmonics.L2_2.scale(0.858086);
  58899. result.scale(1.0 / Math.PI);
  58900. return result;
  58901. };
  58902. SphericalPolynomial.prototype.scale = function (scale) {
  58903. this.x = this.x.scale(scale);
  58904. this.y = this.y.scale(scale);
  58905. this.z = this.z.scale(scale);
  58906. this.xx = this.xx.scale(scale);
  58907. this.yy = this.yy.scale(scale);
  58908. this.zz = this.zz.scale(scale);
  58909. this.yz = this.yz.scale(scale);
  58910. this.zx = this.zx.scale(scale);
  58911. this.xy = this.xy.scale(scale);
  58912. };
  58913. return SphericalPolynomial;
  58914. }());
  58915. BABYLON.SphericalPolynomial = SphericalPolynomial;
  58916. var SphericalHarmonics = (function () {
  58917. function SphericalHarmonics() {
  58918. this.L00 = BABYLON.Vector3.Zero();
  58919. this.L1_1 = BABYLON.Vector3.Zero();
  58920. this.L10 = BABYLON.Vector3.Zero();
  58921. this.L11 = BABYLON.Vector3.Zero();
  58922. this.L2_2 = BABYLON.Vector3.Zero();
  58923. this.L2_1 = BABYLON.Vector3.Zero();
  58924. this.L20 = BABYLON.Vector3.Zero();
  58925. this.L21 = BABYLON.Vector3.Zero();
  58926. this.L22 = BABYLON.Vector3.Zero();
  58927. }
  58928. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  58929. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  58930. var c = colorVector.scale(deltaSolidAngle);
  58931. this.L00 = this.L00.add(c.scale(0.282095));
  58932. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  58933. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  58934. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  58935. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  58936. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  58937. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  58938. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  58939. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  58940. };
  58941. SphericalHarmonics.prototype.scale = function (scale) {
  58942. this.L00 = this.L00.scale(scale);
  58943. this.L1_1 = this.L1_1.scale(scale);
  58944. this.L10 = this.L10.scale(scale);
  58945. this.L11 = this.L11.scale(scale);
  58946. this.L2_2 = this.L2_2.scale(scale);
  58947. this.L2_1 = this.L2_1.scale(scale);
  58948. this.L20 = this.L20.scale(scale);
  58949. this.L21 = this.L21.scale(scale);
  58950. this.L22 = this.L22.scale(scale);
  58951. };
  58952. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  58953. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  58954. //
  58955. // E_lm = A_l * L_lm
  58956. //
  58957. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  58958. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  58959. // the scaling factors are given in equation 9.
  58960. // Constant (Band 0)
  58961. this.L00 = this.L00.scale(3.141593);
  58962. // Linear (Band 1)
  58963. this.L1_1 = this.L1_1.scale(2.094395);
  58964. this.L10 = this.L10.scale(2.094395);
  58965. this.L11 = this.L11.scale(2.094395);
  58966. // Quadratic (Band 2)
  58967. this.L2_2 = this.L2_2.scale(0.785398);
  58968. this.L2_1 = this.L2_1.scale(0.785398);
  58969. this.L20 = this.L20.scale(0.785398);
  58970. this.L21 = this.L21.scale(0.785398);
  58971. this.L22 = this.L22.scale(0.785398);
  58972. };
  58973. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  58974. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  58975. // L = (1/pi) * E * rho
  58976. //
  58977. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  58978. this.scale(1.0 / Math.PI);
  58979. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  58980. // (The pixel shader must apply albedo after texture fetches, etc).
  58981. };
  58982. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  58983. var result = new SphericalHarmonics();
  58984. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  58985. result.L1_1 = polynomial.y.scale(0.977204);
  58986. result.L10 = polynomial.z.scale(0.977204);
  58987. result.L11 = polynomial.x.scale(0.977204);
  58988. result.L2_2 = polynomial.xy.scale(1.16538);
  58989. result.L2_1 = polynomial.yz.scale(1.16538);
  58990. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  58991. result.L21 = polynomial.zx.scale(1.16538);
  58992. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  58993. result.scale(Math.PI);
  58994. return result;
  58995. };
  58996. return SphericalHarmonics;
  58997. }());
  58998. BABYLON.SphericalHarmonics = SphericalHarmonics;
  58999. })(BABYLON || (BABYLON = {}));
  59000. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  59001. var BABYLON;
  59002. (function (BABYLON) {
  59003. var Internals;
  59004. (function (Internals) {
  59005. var FileFaceOrientation = (function () {
  59006. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  59007. this.name = name;
  59008. this.worldAxisForNormal = worldAxisForNormal;
  59009. this.worldAxisForFileX = worldAxisForFileX;
  59010. this.worldAxisForFileY = worldAxisForFileY;
  59011. }
  59012. return FileFaceOrientation;
  59013. }());
  59014. ;
  59015. /**
  59016. * Helper class dealing with the extraction of spherical polynomial dataArray
  59017. * from a cube map.
  59018. */
  59019. var CubeMapToSphericalPolynomialTools = (function () {
  59020. function CubeMapToSphericalPolynomialTools() {
  59021. }
  59022. /**
  59023. * Converts a texture to the according Spherical Polynomial data.
  59024. * This extracts the first 3 orders only as they are the only one used in the lighting.
  59025. *
  59026. * @param texture The texture to extract the information from.
  59027. * @return The Spherical Polynomial data.
  59028. */
  59029. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  59030. if (!texture.isCube) {
  59031. // Only supports cube Textures currently.
  59032. return null;
  59033. }
  59034. var size = texture.getSize().width;
  59035. var right = texture.readPixels(0);
  59036. var left = texture.readPixels(1);
  59037. var up;
  59038. var down;
  59039. if (texture.isRenderTarget) {
  59040. up = texture.readPixels(3);
  59041. down = texture.readPixels(2);
  59042. }
  59043. else {
  59044. up = texture.readPixels(2);
  59045. down = texture.readPixels(3);
  59046. }
  59047. var front = texture.readPixels(4);
  59048. var back = texture.readPixels(5);
  59049. var gammaSpace = texture.gammaSpace;
  59050. // Always read as RGBA.
  59051. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  59052. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59053. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59054. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59055. }
  59056. var cubeInfo = {
  59057. size: size,
  59058. right: right,
  59059. left: left,
  59060. up: up,
  59061. down: down,
  59062. front: front,
  59063. back: back,
  59064. format: format,
  59065. type: type,
  59066. gammaSpace: gammaSpace,
  59067. };
  59068. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  59069. };
  59070. /**
  59071. * Converts a cubemap to the according Spherical Polynomial data.
  59072. * This extracts the first 3 orders only as they are the only one used in the lighting.
  59073. *
  59074. * @param cubeInfo The Cube map to extract the information from.
  59075. * @return The Spherical Polynomial data.
  59076. */
  59077. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  59078. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  59079. var totalSolidAngle = 0.0;
  59080. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  59081. var du = 2.0 / cubeInfo.size;
  59082. var dv = du;
  59083. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  59084. var minUV = du * 0.5 - 1.0;
  59085. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59086. var fileFace = this.FileFaces[faceIndex];
  59087. var dataArray = cubeInfo[fileFace.name];
  59088. var v = minUV;
  59089. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  59090. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  59091. // Because SP is still linear, so summation is fine in that basis.
  59092. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  59093. for (var y = 0; y < cubeInfo.size; y++) {
  59094. var u = minUV;
  59095. for (var x = 0; x < cubeInfo.size; x++) {
  59096. // World direction (not normalised)
  59097. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  59098. worldDirection.normalize();
  59099. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  59100. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  59101. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  59102. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  59103. // Handle Integer types.
  59104. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59105. r /= 255;
  59106. g /= 255;
  59107. b /= 255;
  59108. }
  59109. // Handle Gamma space textures.
  59110. if (cubeInfo.gammaSpace) {
  59111. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  59112. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  59113. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  59114. }
  59115. var color = new BABYLON.Color3(r, g, b);
  59116. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  59117. totalSolidAngle += deltaSolidAngle;
  59118. u += du;
  59119. }
  59120. v += dv;
  59121. }
  59122. }
  59123. // Solid angle for entire sphere is 4*pi
  59124. var sphereSolidAngle = 4.0 * Math.PI;
  59125. // Adjust the solid angle to allow for how many faces we processed.
  59126. var facesProcessed = 6.0;
  59127. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  59128. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  59129. // This is needed because the numerical integration over the cube uses a
  59130. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  59131. // and also to compensate for accumulative error due to float precision in the summation.
  59132. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  59133. sphericalHarmonics.scale(correctionFactor);
  59134. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  59135. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  59136. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  59137. };
  59138. return CubeMapToSphericalPolynomialTools;
  59139. }());
  59140. CubeMapToSphericalPolynomialTools.FileFaces = [
  59141. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  59142. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  59143. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  59144. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  59145. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  59146. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  59147. ];
  59148. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  59149. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59150. })(BABYLON || (BABYLON = {}));
  59151. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  59152. var BABYLON;
  59153. (function (BABYLON) {
  59154. var Internals;
  59155. (function (Internals) {
  59156. /**
  59157. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  59158. */
  59159. var PanoramaToCubeMapTools = (function () {
  59160. function PanoramaToCubeMapTools() {
  59161. }
  59162. /**
  59163. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  59164. *
  59165. * @param float32Array The source data.
  59166. * @param inputWidth The width of the input panorama.
  59167. * @param inputhHeight The height of the input panorama.
  59168. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  59169. * @return The cubemap data
  59170. */
  59171. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  59172. if (!float32Array) {
  59173. throw "ConvertPanoramaToCubemap: input cannot be null";
  59174. }
  59175. if (float32Array.length != inputWidth * inputHeight * 3) {
  59176. throw "ConvertPanoramaToCubemap: input size is wrong";
  59177. }
  59178. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  59179. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  59180. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  59181. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  59182. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  59183. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  59184. return {
  59185. front: textureFront,
  59186. back: textureBack,
  59187. left: textureLeft,
  59188. right: textureRight,
  59189. up: textureUp,
  59190. down: textureDown,
  59191. size: size,
  59192. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  59193. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  59194. gammaSpace: false,
  59195. };
  59196. };
  59197. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  59198. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  59199. var textureArray = new Float32Array(buffer);
  59200. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  59201. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  59202. var dy = 1 / texSize;
  59203. var fy = 0;
  59204. for (var y = 0; y < texSize; y++) {
  59205. var xv1 = faceData[0];
  59206. var xv2 = faceData[2];
  59207. for (var x = 0; x < texSize; x++) {
  59208. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  59209. v.normalize();
  59210. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  59211. // 3 channels per pixels
  59212. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  59213. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  59214. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  59215. xv1 = xv1.add(rotDX1);
  59216. xv2 = xv2.add(rotDX2);
  59217. }
  59218. fy += dy;
  59219. }
  59220. return textureArray;
  59221. };
  59222. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  59223. var theta = Math.atan2(vDir.z, vDir.x);
  59224. var phi = Math.acos(vDir.y);
  59225. while (theta < -Math.PI)
  59226. theta += 2 * Math.PI;
  59227. while (theta > Math.PI)
  59228. theta -= 2 * Math.PI;
  59229. var dx = theta / Math.PI;
  59230. var dy = phi / Math.PI;
  59231. // recenter.
  59232. dx = dx * 0.5 + 0.5;
  59233. var px = Math.round(dx * inputWidth);
  59234. if (px < 0)
  59235. px = 0;
  59236. else if (px >= inputWidth)
  59237. px = inputWidth - 1;
  59238. var py = Math.round(dy * inputHeight);
  59239. if (py < 0)
  59240. py = 0;
  59241. else if (py >= inputHeight)
  59242. py = inputHeight - 1;
  59243. var inputY = (inputHeight - py - 1);
  59244. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  59245. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  59246. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  59247. return {
  59248. r: r,
  59249. g: g,
  59250. b: b
  59251. };
  59252. };
  59253. return PanoramaToCubeMapTools;
  59254. }());
  59255. PanoramaToCubeMapTools.FACE_FRONT = [
  59256. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  59257. new BABYLON.Vector3(1.0, -1.0, -1.0),
  59258. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  59259. new BABYLON.Vector3(1.0, 1.0, -1.0)
  59260. ];
  59261. PanoramaToCubeMapTools.FACE_BACK = [
  59262. new BABYLON.Vector3(1.0, -1.0, 1.0),
  59263. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  59264. new BABYLON.Vector3(1.0, 1.0, 1.0),
  59265. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  59266. ];
  59267. PanoramaToCubeMapTools.FACE_RIGHT = [
  59268. new BABYLON.Vector3(1.0, -1.0, -1.0),
  59269. new BABYLON.Vector3(1.0, -1.0, 1.0),
  59270. new BABYLON.Vector3(1.0, 1.0, -1.0),
  59271. new BABYLON.Vector3(1.0, 1.0, 1.0)
  59272. ];
  59273. PanoramaToCubeMapTools.FACE_LEFT = [
  59274. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  59275. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  59276. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  59277. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  59278. ];
  59279. PanoramaToCubeMapTools.FACE_DOWN = [
  59280. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  59281. new BABYLON.Vector3(1.0, 1.0, -1.0),
  59282. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  59283. new BABYLON.Vector3(1.0, 1.0, 1.0)
  59284. ];
  59285. PanoramaToCubeMapTools.FACE_UP = [
  59286. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  59287. new BABYLON.Vector3(1.0, -1.0, 1.0),
  59288. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  59289. new BABYLON.Vector3(1.0, -1.0, -1.0)
  59290. ];
  59291. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  59292. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59293. })(BABYLON || (BABYLON = {}));
  59294. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  59295. var BABYLON;
  59296. (function (BABYLON) {
  59297. var Internals;
  59298. (function (Internals) {
  59299. ;
  59300. /**
  59301. * This groups tools to convert HDR texture to native colors array.
  59302. */
  59303. var HDRTools = (function () {
  59304. function HDRTools() {
  59305. }
  59306. HDRTools.Ldexp = function (mantissa, exponent) {
  59307. if (exponent > 1023) {
  59308. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  59309. }
  59310. if (exponent < -1074) {
  59311. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  59312. }
  59313. return mantissa * Math.pow(2, exponent);
  59314. };
  59315. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  59316. if (exponent > 0) {
  59317. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  59318. float32array[index + 0] = red * exponent;
  59319. float32array[index + 1] = green * exponent;
  59320. float32array[index + 2] = blue * exponent;
  59321. }
  59322. else {
  59323. float32array[index + 0] = 0;
  59324. float32array[index + 1] = 0;
  59325. float32array[index + 2] = 0;
  59326. }
  59327. };
  59328. HDRTools.readStringLine = function (uint8array, startIndex) {
  59329. var line = "";
  59330. var character = "";
  59331. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  59332. character = String.fromCharCode(uint8array[i]);
  59333. if (character == "\n") {
  59334. break;
  59335. }
  59336. line += character;
  59337. }
  59338. return line;
  59339. };
  59340. /**
  59341. * Reads header information from an RGBE texture stored in a native array.
  59342. * More information on this format are available here:
  59343. * https://en.wikipedia.org/wiki/RGBE_image_format
  59344. *
  59345. * @param uint8array The binary file stored in native array.
  59346. * @return The header information.
  59347. */
  59348. HDRTools.RGBE_ReadHeader = function (uint8array) {
  59349. var height = 0;
  59350. var width = 0;
  59351. var line = this.readStringLine(uint8array, 0);
  59352. if (line[0] != '#' || line[1] != '?') {
  59353. throw "Bad HDR Format.";
  59354. }
  59355. var endOfHeader = false;
  59356. var findFormat = false;
  59357. var lineIndex = 0;
  59358. do {
  59359. lineIndex += (line.length + 1);
  59360. line = this.readStringLine(uint8array, lineIndex);
  59361. if (line == "FORMAT=32-bit_rle_rgbe") {
  59362. findFormat = true;
  59363. }
  59364. else if (line.length == 0) {
  59365. endOfHeader = true;
  59366. }
  59367. } while (!endOfHeader);
  59368. if (!findFormat) {
  59369. throw "HDR Bad header format, unsupported FORMAT";
  59370. }
  59371. lineIndex += (line.length + 1);
  59372. line = this.readStringLine(uint8array, lineIndex);
  59373. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  59374. var match = sizeRegexp.exec(line);
  59375. // TODO. Support +Y and -X if needed.
  59376. if (match.length < 3) {
  59377. throw "HDR Bad header format, no size";
  59378. }
  59379. width = parseInt(match[2]);
  59380. height = parseInt(match[1]);
  59381. if (width < 8 || width > 0x7fff) {
  59382. throw "HDR Bad header format, unsupported size";
  59383. }
  59384. lineIndex += (line.length + 1);
  59385. return {
  59386. height: height,
  59387. width: width,
  59388. dataPosition: lineIndex
  59389. };
  59390. };
  59391. /**
  59392. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  59393. * This RGBE texture needs to store the information as a panorama.
  59394. *
  59395. * More information on this format are available here:
  59396. * https://en.wikipedia.org/wiki/RGBE_image_format
  59397. *
  59398. * @param buffer The binary file stored in an array buffer.
  59399. * @param size The expected size of the extracted cubemap.
  59400. * @return The Cube Map information.
  59401. */
  59402. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  59403. var uint8array = new Uint8Array(buffer);
  59404. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  59405. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  59406. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  59407. return cubeMapData;
  59408. };
  59409. /**
  59410. * Returns the pixels data extracted from an RGBE texture.
  59411. * This pixels will be stored left to right up to down in the R G B order in one array.
  59412. *
  59413. * More information on this format are available here:
  59414. * https://en.wikipedia.org/wiki/RGBE_image_format
  59415. *
  59416. * @param uint8array The binary file stored in an array buffer.
  59417. * @param hdrInfo The header information of the file.
  59418. * @return The pixels data in RGB right to left up to down order.
  59419. */
  59420. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  59421. // Keep for multi format supports.
  59422. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  59423. };
  59424. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  59425. var num_scanlines = hdrInfo.height;
  59426. var scanline_width = hdrInfo.width;
  59427. var a, b, c, d, count;
  59428. var dataIndex = hdrInfo.dataPosition;
  59429. var index = 0, endIndex = 0, i = 0;
  59430. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  59431. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  59432. // 3 channels of 4 bytes per pixel in float.
  59433. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  59434. var resultArray = new Float32Array(resultBuffer);
  59435. // read in each successive scanline
  59436. while (num_scanlines > 0) {
  59437. a = uint8array[dataIndex++];
  59438. b = uint8array[dataIndex++];
  59439. c = uint8array[dataIndex++];
  59440. d = uint8array[dataIndex++];
  59441. if (a != 2 || b != 2 || (c & 0x80)) {
  59442. // this file is not run length encoded
  59443. throw "HDR Bad header format, not RLE";
  59444. }
  59445. if (((c << 8) | d) != scanline_width) {
  59446. throw "HDR Bad header format, wrong scan line width";
  59447. }
  59448. index = 0;
  59449. // read each of the four channels for the scanline into the buffer
  59450. for (i = 0; i < 4; i++) {
  59451. endIndex = (i + 1) * scanline_width;
  59452. while (index < endIndex) {
  59453. a = uint8array[dataIndex++];
  59454. b = uint8array[dataIndex++];
  59455. if (a > 128) {
  59456. // a run of the same value
  59457. count = a - 128;
  59458. if ((count == 0) || (count > endIndex - index)) {
  59459. throw "HDR Bad Format, bad scanline data (run)";
  59460. }
  59461. while (count-- > 0) {
  59462. scanLineArray[index++] = b;
  59463. }
  59464. }
  59465. else {
  59466. // a non-run
  59467. count = a;
  59468. if ((count == 0) || (count > endIndex - index)) {
  59469. throw "HDR Bad Format, bad scanline data (non-run)";
  59470. }
  59471. scanLineArray[index++] = b;
  59472. if (--count > 0) {
  59473. for (var j = 0; j < count; j++) {
  59474. scanLineArray[index++] = uint8array[dataIndex++];
  59475. }
  59476. }
  59477. }
  59478. }
  59479. }
  59480. // now convert data from buffer into floats
  59481. for (i = 0; i < scanline_width; i++) {
  59482. a = scanLineArray[i];
  59483. b = scanLineArray[i + scanline_width];
  59484. c = scanLineArray[i + 2 * scanline_width];
  59485. d = scanLineArray[i + 3 * scanline_width];
  59486. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  59487. }
  59488. num_scanlines--;
  59489. }
  59490. return resultArray;
  59491. };
  59492. return HDRTools;
  59493. }());
  59494. Internals.HDRTools = HDRTools;
  59495. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59496. })(BABYLON || (BABYLON = {}));
  59497. //# sourceMappingURL=babylon.hdr.js.map
  59498. var BABYLON;
  59499. (function (BABYLON) {
  59500. /**
  59501. * This represents a texture coming from an HDR input.
  59502. *
  59503. * The only supported format is currently panorama picture stored in RGBE format.
  59504. * Example of such files can be found on HDRLib: http://hdrlib.com/
  59505. */
  59506. var HDRCubeTexture = (function (_super) {
  59507. __extends(HDRCubeTexture, _super);
  59508. /**
  59509. * Instantiates an HDRTexture from the following parameters.
  59510. *
  59511. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  59512. * @param scene The scene the texture will be used in
  59513. * @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.
  59514. * @param noMipmap Forces to not generate the mipmap if true
  59515. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  59516. * @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)
  59517. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  59518. */
  59519. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  59520. if (noMipmap === void 0) { noMipmap = false; }
  59521. if (generateHarmonics === void 0) { generateHarmonics = true; }
  59522. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  59523. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  59524. if (onLoad === void 0) { onLoad = null; }
  59525. if (onError === void 0) { onError = null; }
  59526. var _this = _super.call(this, scene) || this;
  59527. _this._useInGammaSpace = false;
  59528. _this._generateHarmonics = true;
  59529. _this._isBABYLONPreprocessed = false;
  59530. _this._onLoad = null;
  59531. _this._onError = null;
  59532. /**
  59533. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  59534. */
  59535. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  59536. /**
  59537. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  59538. * This is usefull at run time to apply the good shader.
  59539. */
  59540. _this.isPMREM = false;
  59541. _this._isBlocking = true;
  59542. if (!url) {
  59543. return _this;
  59544. }
  59545. _this.name = url;
  59546. _this.url = url;
  59547. _this.hasAlpha = false;
  59548. _this.isCube = true;
  59549. _this._textureMatrix = BABYLON.Matrix.Identity();
  59550. _this._onLoad = onLoad;
  59551. _this._onError = onError;
  59552. _this.gammaSpace = false;
  59553. if (size) {
  59554. _this._isBABYLONPreprocessed = false;
  59555. _this._noMipmap = noMipmap;
  59556. _this._size = size;
  59557. _this._useInGammaSpace = useInGammaSpace;
  59558. _this._usePMREMGenerator = usePMREMGenerator &&
  59559. scene.getEngine().getCaps().textureLOD &&
  59560. _this.getScene().getEngine().getCaps().textureFloat &&
  59561. !_this._useInGammaSpace;
  59562. }
  59563. else {
  59564. _this._isBABYLONPreprocessed = true;
  59565. _this._noMipmap = false;
  59566. _this._useInGammaSpace = false;
  59567. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  59568. _this.getScene().getEngine().getCaps().textureFloat &&
  59569. !_this._useInGammaSpace;
  59570. }
  59571. _this.isPMREM = _this._usePMREMGenerator;
  59572. _this._texture = _this._getFromCache(url, _this._noMipmap);
  59573. if (!_this._texture) {
  59574. if (!scene.useDelayedTextureLoading) {
  59575. _this.loadTexture();
  59576. }
  59577. else {
  59578. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59579. }
  59580. }
  59581. return _this;
  59582. }
  59583. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  59584. /**
  59585. * Gets wether or not the texture is blocking during loading.
  59586. */
  59587. get: function () {
  59588. return this._isBlocking;
  59589. },
  59590. /**
  59591. * Sets wether or not the texture is blocking during loading.
  59592. */
  59593. set: function (value) {
  59594. this._isBlocking = value;
  59595. },
  59596. enumerable: true,
  59597. configurable: true
  59598. });
  59599. /**
  59600. * Occurs when the file is a preprocessed .babylon.hdr file.
  59601. */
  59602. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  59603. var _this = this;
  59604. var mipLevels = 0;
  59605. var floatArrayView = null;
  59606. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  59607. var mips = [];
  59608. var startIndex = 30;
  59609. for (var level = 0; level < mipLevels; level++) {
  59610. mips.push([]);
  59611. // Fill each pixel of the mip level.
  59612. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  59613. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59614. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  59615. mips[level].push(faceData);
  59616. startIndex += faceSize;
  59617. }
  59618. }
  59619. return mips;
  59620. } : null;
  59621. var callback = function (buffer) {
  59622. // Create Native Array Views
  59623. var intArrayView = new Int32Array(buffer);
  59624. floatArrayView = new Float32Array(buffer);
  59625. // Fill header.
  59626. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  59627. _this._size = intArrayView[1]; // CubeMap max mip face size.
  59628. // Update Texture Information.
  59629. _this._texture.updateSize(_this._size, _this._size);
  59630. // Fill polynomial information.
  59631. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  59632. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  59633. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  59634. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  59635. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  59636. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  59637. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  59638. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  59639. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  59640. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  59641. _this.sphericalPolynomial = sphericalPolynomial;
  59642. // Fill pixel data.
  59643. mipLevels = intArrayView[29]; // Number of mip levels.
  59644. var startIndex = 30;
  59645. var data = [];
  59646. var faceSize = Math.pow(_this._size, 2) * 3;
  59647. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59648. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  59649. startIndex += faceSize;
  59650. }
  59651. var results = [];
  59652. var byteArray = null;
  59653. // Push each faces.
  59654. for (var k = 0; k < 6; k++) {
  59655. var dataFace = null;
  59656. // To be deprecated.
  59657. if (version === 1) {
  59658. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  59659. dataFace = data[j];
  59660. }
  59661. // If special cases.
  59662. if (!mipmapGenerator) {
  59663. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59664. // 3 channels of 1 bytes per pixel in bytes.
  59665. var byteBuffer = new ArrayBuffer(faceSize);
  59666. byteArray = new Uint8Array(byteBuffer);
  59667. }
  59668. for (var i = 0; i < _this._size * _this._size; i++) {
  59669. // Put in gamma space if requested.
  59670. if (_this._useInGammaSpace) {
  59671. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59672. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59673. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59674. }
  59675. // Convert to int texture for fallback.
  59676. if (byteArray) {
  59677. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59678. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59679. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59680. // May use luminance instead if the result is not accurate.
  59681. var max = Math.max(Math.max(r, g), b);
  59682. if (max > 255) {
  59683. var scale = 255 / max;
  59684. r *= scale;
  59685. g *= scale;
  59686. b *= scale;
  59687. }
  59688. byteArray[(i * 3) + 0] = r;
  59689. byteArray[(i * 3) + 1] = g;
  59690. byteArray[(i * 3) + 2] = b;
  59691. }
  59692. }
  59693. }
  59694. // Fill the array accordingly.
  59695. if (byteArray) {
  59696. results.push(byteArray);
  59697. }
  59698. else {
  59699. results.push(dataFace);
  59700. }
  59701. }
  59702. return results;
  59703. };
  59704. 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);
  59705. };
  59706. /**
  59707. * Occurs when the file is raw .hdr file.
  59708. */
  59709. HDRCubeTexture.prototype.loadHDRTexture = function () {
  59710. var _this = this;
  59711. var callback = function (buffer) {
  59712. // Extract the raw linear data.
  59713. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  59714. // Generate harmonics if needed.
  59715. if (_this._generateHarmonics) {
  59716. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  59717. _this.sphericalPolynomial = sphericalPolynomial;
  59718. }
  59719. var results = [];
  59720. var byteArray = null;
  59721. // Push each faces.
  59722. for (var j = 0; j < 6; j++) {
  59723. // Create uintarray fallback.
  59724. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59725. // 3 channels of 1 bytes per pixel in bytes.
  59726. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  59727. byteArray = new Uint8Array(byteBuffer);
  59728. }
  59729. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  59730. // If special cases.
  59731. if (_this._useInGammaSpace || byteArray) {
  59732. for (var i = 0; i < _this._size * _this._size; i++) {
  59733. // Put in gamma space if requested.
  59734. if (_this._useInGammaSpace) {
  59735. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59736. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59737. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59738. }
  59739. // Convert to int texture for fallback.
  59740. if (byteArray) {
  59741. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59742. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59743. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59744. // May use luminance instead if the result is not accurate.
  59745. var max = Math.max(Math.max(r, g), b);
  59746. if (max > 255) {
  59747. var scale = 255 / max;
  59748. r *= scale;
  59749. g *= scale;
  59750. b *= scale;
  59751. }
  59752. byteArray[(i * 3) + 0] = r;
  59753. byteArray[(i * 3) + 1] = g;
  59754. byteArray[(i * 3) + 2] = b;
  59755. }
  59756. }
  59757. }
  59758. if (byteArray) {
  59759. results.push(byteArray);
  59760. }
  59761. else {
  59762. results.push(dataFace);
  59763. }
  59764. }
  59765. return results;
  59766. };
  59767. var mipmapGenerator = null;
  59768. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  59769. // if (!this._noMipmap &&
  59770. // this._usePMREMGenerator) {
  59771. // mipmapGenerator = (data: ArrayBufferView[]) => {
  59772. // // Custom setup of the generator matching with the PBR shader values.
  59773. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  59774. // this._size,
  59775. // this._size,
  59776. // 0,
  59777. // 3,
  59778. // this.getScene().getEngine().getCaps().textureFloat,
  59779. // 2048,
  59780. // 0.25,
  59781. // false,
  59782. // true);
  59783. // return generator.filterCubeMap();
  59784. // };
  59785. // }
  59786. 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);
  59787. };
  59788. /**
  59789. * Starts the loading process of the texture.
  59790. */
  59791. HDRCubeTexture.prototype.loadTexture = function () {
  59792. if (this._isBABYLONPreprocessed) {
  59793. this.loadBabylonTexture();
  59794. }
  59795. else {
  59796. this.loadHDRTexture();
  59797. }
  59798. };
  59799. HDRCubeTexture.prototype.clone = function () {
  59800. var size = this._isBABYLONPreprocessed ? null : this._size;
  59801. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  59802. // Base texture
  59803. newTexture.level = this.level;
  59804. newTexture.wrapU = this.wrapU;
  59805. newTexture.wrapV = this.wrapV;
  59806. newTexture.coordinatesIndex = this.coordinatesIndex;
  59807. newTexture.coordinatesMode = this.coordinatesMode;
  59808. return newTexture;
  59809. };
  59810. // Methods
  59811. HDRCubeTexture.prototype.delayLoad = function () {
  59812. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59813. return;
  59814. }
  59815. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59816. this._texture = this._getFromCache(this.url, this._noMipmap);
  59817. if (!this._texture) {
  59818. this.loadTexture();
  59819. }
  59820. };
  59821. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  59822. return this._textureMatrix;
  59823. };
  59824. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  59825. this._textureMatrix = value;
  59826. };
  59827. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59828. var texture = null;
  59829. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  59830. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  59831. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  59832. texture.name = parsedTexture.name;
  59833. texture.hasAlpha = parsedTexture.hasAlpha;
  59834. texture.level = parsedTexture.level;
  59835. texture.coordinatesMode = parsedTexture.coordinatesMode;
  59836. texture.isBlocking = parsedTexture.isBlocking;
  59837. }
  59838. return texture;
  59839. };
  59840. HDRCubeTexture.prototype.serialize = function () {
  59841. if (!this.name) {
  59842. return null;
  59843. }
  59844. var serializationObject = {};
  59845. serializationObject.name = this.name;
  59846. serializationObject.hasAlpha = this.hasAlpha;
  59847. serializationObject.isCube = true;
  59848. serializationObject.level = this.level;
  59849. serializationObject.size = this._size;
  59850. serializationObject.coordinatesMode = this.coordinatesMode;
  59851. serializationObject.useInGammaSpace = this._useInGammaSpace;
  59852. serializationObject.generateHarmonics = this._generateHarmonics;
  59853. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  59854. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  59855. serializationObject.customType = "BABYLON.HDRCubeTexture";
  59856. serializationObject.noMipmap = this._noMipmap;
  59857. serializationObject.isBlocking = this._isBlocking;
  59858. return serializationObject;
  59859. };
  59860. /**
  59861. * Saves as a file the data contained in the texture in a binary format.
  59862. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59863. * as the spherical used in the lighting.
  59864. * @param url The HDR file url.
  59865. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59866. * @param onError Method called if any error happens during download.
  59867. * @return The packed binary data.
  59868. */
  59869. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  59870. if (onError === void 0) { onError = null; }
  59871. var callback = function (buffer) {
  59872. var data = new Blob([buffer], { type: 'application/octet-stream' });
  59873. // Returns a URL you can use as a href.
  59874. var objUrl = window.URL.createObjectURL(data);
  59875. // Simulates a link to it and click to dowload.
  59876. var a = document.createElement("a");
  59877. document.body.appendChild(a);
  59878. a.style.display = "none";
  59879. a.href = objUrl;
  59880. a.download = "envmap.babylon.hdr";
  59881. a.click();
  59882. };
  59883. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  59884. };
  59885. /**
  59886. * Serializes the data contained in the texture in a binary format.
  59887. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59888. * as the spherical used in the lighting.
  59889. * @param url The HDR file url.
  59890. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59891. * @param onError Method called if any error happens during download.
  59892. * @return The packed binary data.
  59893. */
  59894. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  59895. if (onError === void 0) { onError = null; }
  59896. // Needs the url tho create the texture.
  59897. if (!url) {
  59898. return null;
  59899. }
  59900. // Check Power of two size.
  59901. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  59902. return null;
  59903. }
  59904. // Coming Back in 3.1.
  59905. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  59906. return null;
  59907. };
  59908. return HDRCubeTexture;
  59909. }(BABYLON.BaseTexture));
  59910. HDRCubeTexture._facesMapping = [
  59911. "right",
  59912. "left",
  59913. "up",
  59914. "down",
  59915. "front",
  59916. "back"
  59917. ];
  59918. BABYLON.HDRCubeTexture = HDRCubeTexture;
  59919. })(BABYLON || (BABYLON = {}));
  59920. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  59921. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  59922. // Huge respect for a such great lib.
  59923. // Earcut license:
  59924. // Copyright (c) 2016, Mapbox
  59925. //
  59926. // Permission to use, copy, modify, and/or distribute this software for any purpose
  59927. // with or without fee is hereby granted, provided that the above copyright notice
  59928. // and this permission notice appear in all copies.
  59929. //
  59930. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  59931. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  59932. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  59933. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  59934. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  59935. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  59936. // THIS SOFTWARE.
  59937. var Earcut;
  59938. (function (Earcut) {
  59939. /**
  59940. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  59941. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  59942. * @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).
  59943. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  59944. */
  59945. function earcut(data, holeIndices, dim) {
  59946. dim = dim || 2;
  59947. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  59948. if (!outerNode)
  59949. return triangles;
  59950. var minX, minY, maxX, maxY, x, y, size;
  59951. if (hasHoles)
  59952. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  59953. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  59954. if (data.length > 80 * dim) {
  59955. minX = maxX = data[0];
  59956. minY = maxY = data[1];
  59957. for (var i = dim; i < outerLen; i += dim) {
  59958. x = data[i];
  59959. y = data[i + 1];
  59960. if (x < minX)
  59961. minX = x;
  59962. if (y < minY)
  59963. minY = y;
  59964. if (x > maxX)
  59965. maxX = x;
  59966. if (y > maxY)
  59967. maxY = y;
  59968. }
  59969. // minX, minY and size are later used to transform coords into integers for z-order calculation
  59970. size = Math.max(maxX - minX, maxY - minY);
  59971. }
  59972. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  59973. return triangles;
  59974. }
  59975. Earcut.earcut = earcut;
  59976. // create a circular doubly linked list from polygon points in the specified winding order
  59977. function linkedList(data, start, end, dim, clockwise) {
  59978. var i, last;
  59979. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  59980. for (i = start; i < end; i += dim)
  59981. last = insertNode(i, data[i], data[i + 1], last);
  59982. }
  59983. else {
  59984. for (i = end - dim; i >= start; i -= dim)
  59985. last = insertNode(i, data[i], data[i + 1], last);
  59986. }
  59987. if (last && equals(last, last.next)) {
  59988. removeNode(last);
  59989. last = last.next;
  59990. }
  59991. return last;
  59992. }
  59993. // eliminate colinear or duplicate points
  59994. function filterPoints(start, end) {
  59995. if (!start)
  59996. return start;
  59997. if (!end)
  59998. end = start;
  59999. var p = start, again;
  60000. do {
  60001. again = false;
  60002. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  60003. removeNode(p);
  60004. p = end = p.prev;
  60005. if (p === p.next)
  60006. return null;
  60007. again = true;
  60008. }
  60009. else {
  60010. p = p.next;
  60011. }
  60012. } while (again || p !== end);
  60013. return end;
  60014. }
  60015. // main ear slicing loop which triangulates a polygon (given as a linked list)
  60016. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  60017. if (!ear)
  60018. return;
  60019. // interlink polygon nodes in z-order
  60020. if (!pass && size)
  60021. indexCurve(ear, minX, minY, size);
  60022. var stop = ear, prev, next;
  60023. // iterate through ears, slicing them one by one
  60024. while (ear.prev !== ear.next) {
  60025. prev = ear.prev;
  60026. next = ear.next;
  60027. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  60028. // cut off the triangle
  60029. triangles.push(prev.i / dim);
  60030. triangles.push(ear.i / dim);
  60031. triangles.push(next.i / dim);
  60032. removeNode(ear);
  60033. // skipping the next vertice leads to less sliver triangles
  60034. ear = next.next;
  60035. stop = next.next;
  60036. continue;
  60037. }
  60038. ear = next;
  60039. // if we looped through the whole remaining polygon and can't find any more ears
  60040. if (ear === stop) {
  60041. // try filtering points and slicing again
  60042. if (!pass) {
  60043. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  60044. // if this didn't work, try curing all small self-intersections locally
  60045. }
  60046. else if (pass === 1) {
  60047. ear = cureLocalIntersections(ear, triangles, dim);
  60048. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  60049. // as a last resort, try splitting the remaining polygon into two
  60050. }
  60051. else if (pass === 2) {
  60052. splitEarcut(ear, triangles, dim, minX, minY, size);
  60053. }
  60054. break;
  60055. }
  60056. }
  60057. }
  60058. // check whether a polygon node forms a valid ear with adjacent nodes
  60059. function isEar(ear) {
  60060. var a = ear.prev, b = ear, c = ear.next;
  60061. if (area(a, b, c) >= 0)
  60062. return false; // reflex, can't be an ear
  60063. // now make sure we don't have other points inside the potential ear
  60064. var p = ear.next.next;
  60065. while (p !== ear.prev) {
  60066. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  60067. area(p.prev, p, p.next) >= 0)
  60068. return false;
  60069. p = p.next;
  60070. }
  60071. return true;
  60072. }
  60073. function isEarHashed(ear, minX, minY, size) {
  60074. var a = ear.prev, b = ear, c = ear.next;
  60075. if (area(a, b, c) >= 0)
  60076. return false; // reflex, can't be an ear
  60077. // triangle bbox; min & max are calculated like this for speed
  60078. 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);
  60079. // z-order range for the current triangle bbox;
  60080. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  60081. // first look for points inside the triangle in increasing z-order
  60082. var p = ear.nextZ;
  60083. while (p && p.z <= maxZ) {
  60084. if (p !== ear.prev &&
  60085. p !== ear.next &&
  60086. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  60087. area(p.prev, p, p.next) >= 0)
  60088. return false;
  60089. p = p.nextZ;
  60090. }
  60091. // then look for points in decreasing z-order
  60092. p = ear.prevZ;
  60093. while (p && p.z >= minZ) {
  60094. if (p !== ear.prev &&
  60095. p !== ear.next &&
  60096. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  60097. area(p.prev, p, p.next) >= 0)
  60098. return false;
  60099. p = p.prevZ;
  60100. }
  60101. return true;
  60102. }
  60103. // go through all polygon nodes and cure small local self-intersections
  60104. function cureLocalIntersections(start, triangles, dim) {
  60105. var p = start;
  60106. do {
  60107. var a = p.prev, b = p.next.next;
  60108. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  60109. triangles.push(a.i / dim);
  60110. triangles.push(p.i / dim);
  60111. triangles.push(b.i / dim);
  60112. // remove two nodes involved
  60113. removeNode(p);
  60114. removeNode(p.next);
  60115. p = start = b;
  60116. }
  60117. p = p.next;
  60118. } while (p !== start);
  60119. return p;
  60120. }
  60121. // try splitting polygon into two and triangulate them independently
  60122. function splitEarcut(start, triangles, dim, minX, minY, size) {
  60123. // look for a valid diagonal that divides the polygon into two
  60124. var a = start;
  60125. do {
  60126. var b = a.next.next;
  60127. while (b !== a.prev) {
  60128. if (a.i !== b.i && isValidDiagonal(a, b)) {
  60129. // split the polygon in two by the diagonal
  60130. var c = splitPolygon(a, b);
  60131. // filter colinear points around the cuts
  60132. a = filterPoints(a, a.next);
  60133. c = filterPoints(c, c.next);
  60134. // run earcut on each half
  60135. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  60136. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  60137. return;
  60138. }
  60139. b = b.next;
  60140. }
  60141. a = a.next;
  60142. } while (a !== start);
  60143. }
  60144. // link every hole into the outer loop, producing a single-ring polygon without holes
  60145. function eliminateHoles(data, holeIndices, outerNode, dim) {
  60146. var queue = [], i, len, start, end, list;
  60147. for (i = 0, len = holeIndices.length; i < len; i++) {
  60148. start = holeIndices[i] * dim;
  60149. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  60150. list = linkedList(data, start, end, dim, false);
  60151. if (list === list.next)
  60152. list.steiner = true;
  60153. queue.push(getLeftmost(list));
  60154. }
  60155. queue.sort(compareX);
  60156. // process holes from left to right
  60157. for (i = 0; i < queue.length; i++) {
  60158. eliminateHole(queue[i], outerNode);
  60159. outerNode = filterPoints(outerNode, outerNode.next);
  60160. }
  60161. return outerNode;
  60162. }
  60163. function compareX(a, b) {
  60164. return a.x - b.x;
  60165. }
  60166. // find a bridge between vertices that connects hole with an outer ring and and link it
  60167. function eliminateHole(hole, outerNode) {
  60168. outerNode = findHoleBridge(hole, outerNode);
  60169. if (outerNode) {
  60170. var b = splitPolygon(outerNode, hole);
  60171. filterPoints(b, b.next);
  60172. }
  60173. }
  60174. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  60175. function findHoleBridge(hole, outerNode) {
  60176. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  60177. // find a segment intersected by a ray from the hole's leftmost point to the left;
  60178. // segment's endpoint with lesser x will be potential connection point
  60179. do {
  60180. if (hy <= p.y && hy >= p.next.y) {
  60181. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  60182. if (x <= hx && x > qx) {
  60183. qx = x;
  60184. if (x === hx) {
  60185. if (hy === p.y)
  60186. return p;
  60187. if (hy === p.next.y)
  60188. return p.next;
  60189. }
  60190. m = p.x < p.next.x ? p : p.next;
  60191. }
  60192. }
  60193. p = p.next;
  60194. } while (p !== outerNode);
  60195. if (!m)
  60196. return null;
  60197. if (hx === qx)
  60198. return m.prev; // hole touches outer segment; pick lower endpoint
  60199. // look for points inside the triangle of hole point, segment intersection and endpoint;
  60200. // if there are no points found, we have a valid connection;
  60201. // otherwise choose the point of the minimum angle with the ray as connection point
  60202. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  60203. p = m.next;
  60204. while (p !== stop) {
  60205. if (hx >= p.x &&
  60206. p.x >= mx &&
  60207. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  60208. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  60209. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  60210. m = p;
  60211. tanMin = tan;
  60212. }
  60213. }
  60214. p = p.next;
  60215. }
  60216. return m;
  60217. }
  60218. // interlink polygon nodes in z-order
  60219. function indexCurve(start, minX, minY, size) {
  60220. var p = start;
  60221. do {
  60222. if (p.z === null)
  60223. p.z = zOrder(p.x, p.y, minX, minY, size);
  60224. p.prevZ = p.prev;
  60225. p.nextZ = p.next;
  60226. p = p.next;
  60227. } while (p !== start);
  60228. p.prevZ.nextZ = null;
  60229. p.prevZ = null;
  60230. sortLinked(p);
  60231. }
  60232. // Simon Tatham's linked list merge sort algorithm
  60233. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  60234. function sortLinked(list) {
  60235. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  60236. do {
  60237. p = list;
  60238. list = null;
  60239. tail = null;
  60240. numMerges = 0;
  60241. while (p) {
  60242. numMerges++;
  60243. q = p;
  60244. pSize = 0;
  60245. for (i = 0; i < inSize; i++) {
  60246. pSize++;
  60247. q = q.nextZ;
  60248. if (!q)
  60249. break;
  60250. }
  60251. qSize = inSize;
  60252. while (pSize > 0 || (qSize > 0 && q)) {
  60253. if (pSize === 0) {
  60254. e = q;
  60255. q = q.nextZ;
  60256. qSize--;
  60257. }
  60258. else if (qSize === 0 || !q) {
  60259. e = p;
  60260. p = p.nextZ;
  60261. pSize--;
  60262. }
  60263. else if (p.z <= q.z) {
  60264. e = p;
  60265. p = p.nextZ;
  60266. pSize--;
  60267. }
  60268. else {
  60269. e = q;
  60270. q = q.nextZ;
  60271. qSize--;
  60272. }
  60273. if (tail)
  60274. tail.nextZ = e;
  60275. else
  60276. list = e;
  60277. e.prevZ = tail;
  60278. tail = e;
  60279. }
  60280. p = q;
  60281. }
  60282. tail.nextZ = null;
  60283. inSize *= 2;
  60284. } while (numMerges > 1);
  60285. return list;
  60286. }
  60287. // z-order of a point given coords and size of the data bounding box
  60288. function zOrder(x, y, minX, minY, size) {
  60289. // coords are transformed into non-negative 15-bit integer range
  60290. x = 32767 * (x - minX) / size;
  60291. y = 32767 * (y - minY) / size;
  60292. x = (x | (x << 8)) & 0x00FF00FF;
  60293. x = (x | (x << 4)) & 0x0F0F0F0F;
  60294. x = (x | (x << 2)) & 0x33333333;
  60295. x = (x | (x << 1)) & 0x55555555;
  60296. y = (y | (y << 8)) & 0x00FF00FF;
  60297. y = (y | (y << 4)) & 0x0F0F0F0F;
  60298. y = (y | (y << 2)) & 0x33333333;
  60299. y = (y | (y << 1)) & 0x55555555;
  60300. return x | (y << 1);
  60301. }
  60302. // find the leftmost node of a polygon ring
  60303. function getLeftmost(start) {
  60304. var p = start, leftmost = start;
  60305. do {
  60306. if (p.x < leftmost.x)
  60307. leftmost = p;
  60308. p = p.next;
  60309. } while (p !== start);
  60310. return leftmost;
  60311. }
  60312. // check if a point lies within a convex triangle
  60313. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  60314. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  60315. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  60316. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  60317. }
  60318. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  60319. function isValidDiagonal(a, b) {
  60320. return a.next.i !== b.i &&
  60321. a.prev.i !== b.i &&
  60322. !intersectsPolygon(a, b) &&
  60323. locallyInside(a, b) &&
  60324. locallyInside(b, a) &&
  60325. middleInside(a, b);
  60326. }
  60327. // signed area of a triangle
  60328. function area(p, q, r) {
  60329. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  60330. }
  60331. // check if two points are equal
  60332. function equals(p1, p2) {
  60333. return p1.x === p2.x && p1.y === p2.y;
  60334. }
  60335. // check if two segments intersect
  60336. function intersects(p1, q1, p2, q2) {
  60337. if ((equals(p1, q1) && equals(p2, q2)) ||
  60338. (equals(p1, q2) && equals(p2, q1)))
  60339. return true;
  60340. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  60341. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  60342. }
  60343. // check if a polygon diagonal intersects any polygon segments
  60344. function intersectsPolygon(a, b) {
  60345. var p = a;
  60346. do {
  60347. if (p.i !== a.i &&
  60348. p.next.i !== a.i &&
  60349. p.i !== b.i &&
  60350. p.next.i !== b.i &&
  60351. intersects(p, p.next, a, b))
  60352. return true;
  60353. p = p.next;
  60354. } while (p !== a);
  60355. return false;
  60356. }
  60357. // check if a polygon diagonal is locally inside the polygon
  60358. function locallyInside(a, b) {
  60359. return area(a.prev, a, a.next) < 0
  60360. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  60361. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  60362. }
  60363. // check if the middle point of a polygon diagonal is inside the polygon
  60364. function middleInside(a, b) {
  60365. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  60366. do {
  60367. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  60368. inside = !inside;
  60369. p = p.next;
  60370. } while (p !== a);
  60371. return inside;
  60372. }
  60373. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  60374. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  60375. function splitPolygon(a, b) {
  60376. 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;
  60377. a.next = b;
  60378. b.prev = a;
  60379. a2.next = an;
  60380. an.prev = a2;
  60381. b2.next = a2;
  60382. a2.prev = b2;
  60383. bp.next = b2;
  60384. b2.prev = bp;
  60385. return b2;
  60386. }
  60387. // create a node and optionally link it with previous one (in a circular doubly linked list)
  60388. function insertNode(i, x, y, last) {
  60389. var p = new Node(i, x, y);
  60390. if (!last) {
  60391. p.prev = p;
  60392. p.next = p;
  60393. }
  60394. else {
  60395. p.next = last.next;
  60396. p.prev = last;
  60397. last.next.prev = p;
  60398. last.next = p;
  60399. }
  60400. return p;
  60401. }
  60402. function removeNode(p) {
  60403. p.next.prev = p.prev;
  60404. p.prev.next = p.next;
  60405. if (p.prevZ)
  60406. p.prevZ.nextZ = p.nextZ;
  60407. if (p.nextZ)
  60408. p.nextZ.prevZ = p.prevZ;
  60409. }
  60410. function Node(i, x, y) {
  60411. // vertice index in coordinates array
  60412. this.i = i;
  60413. // vertex coordinates
  60414. this.x = x;
  60415. this.y = y;
  60416. // previous and next vertice nodes in a polygon ring
  60417. this.prev = null;
  60418. this.next = null;
  60419. // z-order curve value
  60420. this.z = null;
  60421. // previous and next nodes in z-order
  60422. this.prevZ = null;
  60423. this.nextZ = null;
  60424. // indicates whether this is a steiner point
  60425. this.steiner = false;
  60426. }
  60427. /**
  60428. * return a percentage difference between the polygon area and its triangulation area;
  60429. * used to verify correctness of triangulation
  60430. */
  60431. function deviation(data, holeIndices, dim, triangles) {
  60432. var hasHoles = holeIndices && holeIndices.length;
  60433. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  60434. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  60435. if (hasHoles) {
  60436. for (var i = 0, len = holeIndices.length; i < len; i++) {
  60437. var start = holeIndices[i] * dim;
  60438. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  60439. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  60440. }
  60441. }
  60442. var trianglesArea = 0;
  60443. for (i = 0; i < triangles.length; i += 3) {
  60444. var a = triangles[i] * dim;
  60445. var b = triangles[i + 1] * dim;
  60446. var c = triangles[i + 2] * dim;
  60447. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  60448. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  60449. }
  60450. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  60451. }
  60452. Earcut.deviation = deviation;
  60453. ;
  60454. function signedArea(data, start, end, dim) {
  60455. var sum = 0;
  60456. for (var i = start, j = end - dim; i < end; i += dim) {
  60457. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  60458. j = i;
  60459. }
  60460. return sum;
  60461. }
  60462. /**
  60463. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  60464. */
  60465. function flatten(data) {
  60466. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  60467. for (var i = 0; i < data.length; i++) {
  60468. for (var j = 0; j < data[i].length; j++) {
  60469. for (var d = 0; d < dim; d++)
  60470. result.vertices.push(data[i][j][d]);
  60471. }
  60472. if (i > 0) {
  60473. holeIndex += data[i - 1].length;
  60474. result.holes.push(holeIndex);
  60475. }
  60476. }
  60477. return result;
  60478. }
  60479. Earcut.flatten = flatten;
  60480. ;
  60481. })(Earcut || (Earcut = {}));
  60482. //# sourceMappingURL=babylon.earcut.js.map
  60483. /// <reference path="..\Math\babylon.math.ts" />
  60484. var BABYLON;
  60485. (function (BABYLON) {
  60486. var IndexedVector2 = (function (_super) {
  60487. __extends(IndexedVector2, _super);
  60488. function IndexedVector2(original, index) {
  60489. var _this = _super.call(this, original.x, original.y) || this;
  60490. _this.index = index;
  60491. return _this;
  60492. }
  60493. return IndexedVector2;
  60494. }(BABYLON.Vector2));
  60495. var PolygonPoints = (function () {
  60496. function PolygonPoints() {
  60497. this.elements = new Array();
  60498. }
  60499. PolygonPoints.prototype.add = function (originalPoints) {
  60500. var _this = this;
  60501. var result = new Array();
  60502. originalPoints.forEach(function (point) {
  60503. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  60504. var newPoint = new IndexedVector2(point, _this.elements.length);
  60505. result.push(newPoint);
  60506. _this.elements.push(newPoint);
  60507. }
  60508. });
  60509. return result;
  60510. };
  60511. PolygonPoints.prototype.computeBounds = function () {
  60512. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  60513. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  60514. this.elements.forEach(function (point) {
  60515. // x
  60516. if (point.x < lmin.x) {
  60517. lmin.x = point.x;
  60518. }
  60519. else if (point.x > lmax.x) {
  60520. lmax.x = point.x;
  60521. }
  60522. // y
  60523. if (point.y < lmin.y) {
  60524. lmin.y = point.y;
  60525. }
  60526. else if (point.y > lmax.y) {
  60527. lmax.y = point.y;
  60528. }
  60529. });
  60530. return {
  60531. min: lmin,
  60532. max: lmax,
  60533. width: lmax.x - lmin.x,
  60534. height: lmax.y - lmin.y
  60535. };
  60536. };
  60537. return PolygonPoints;
  60538. }());
  60539. var Polygon = (function () {
  60540. function Polygon() {
  60541. }
  60542. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  60543. return [
  60544. new BABYLON.Vector2(xmin, ymin),
  60545. new BABYLON.Vector2(xmax, ymin),
  60546. new BABYLON.Vector2(xmax, ymax),
  60547. new BABYLON.Vector2(xmin, ymax)
  60548. ];
  60549. };
  60550. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  60551. if (cx === void 0) { cx = 0; }
  60552. if (cy === void 0) { cy = 0; }
  60553. if (numberOfSides === void 0) { numberOfSides = 32; }
  60554. var result = new Array();
  60555. var angle = 0;
  60556. var increment = (Math.PI * 2) / numberOfSides;
  60557. for (var i = 0; i < numberOfSides; i++) {
  60558. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  60559. angle -= increment;
  60560. }
  60561. return result;
  60562. };
  60563. Polygon.Parse = function (input) {
  60564. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  60565. var i, result = [];
  60566. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  60567. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  60568. }
  60569. return result;
  60570. };
  60571. Polygon.StartingAt = function (x, y) {
  60572. return BABYLON.Path2.StartingAt(x, y);
  60573. };
  60574. return Polygon;
  60575. }());
  60576. BABYLON.Polygon = Polygon;
  60577. var PolygonMeshBuilder = (function () {
  60578. function PolygonMeshBuilder(name, contours, scene) {
  60579. this._points = new PolygonPoints();
  60580. this._outlinepoints = new PolygonPoints();
  60581. this._holes = [];
  60582. this._epoints = new Array();
  60583. this._eholes = new Array();
  60584. this._name = name;
  60585. this._scene = scene;
  60586. var points;
  60587. if (contours instanceof BABYLON.Path2) {
  60588. points = contours.getPoints();
  60589. }
  60590. else {
  60591. points = contours;
  60592. }
  60593. this._addToepoint(points);
  60594. this._points.add(points);
  60595. this._outlinepoints.add(points);
  60596. }
  60597. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  60598. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  60599. var p = points_1[_i];
  60600. this._epoints.push(p.x, p.y);
  60601. }
  60602. };
  60603. PolygonMeshBuilder.prototype.addHole = function (hole) {
  60604. this._points.add(hole);
  60605. var holepoints = new PolygonPoints();
  60606. holepoints.add(hole);
  60607. this._holes.push(holepoints);
  60608. this._eholes.push(this._epoints.length / 2);
  60609. this._addToepoint(hole);
  60610. return this;
  60611. };
  60612. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  60613. var _this = this;
  60614. if (updatable === void 0) { updatable = false; }
  60615. var result = new BABYLON.Mesh(this._name, this._scene);
  60616. var normals = [];
  60617. var positions = [];
  60618. var uvs = [];
  60619. var bounds = this._points.computeBounds();
  60620. this._points.elements.forEach(function (p) {
  60621. normals.push(0, 1.0, 0);
  60622. positions.push(p.x, 0, p.y);
  60623. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  60624. });
  60625. var indices = [];
  60626. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  60627. for (var i = 0; i < res.length; i++) {
  60628. indices.push(res[i]);
  60629. }
  60630. if (depth > 0) {
  60631. var positionscount = (positions.length / 3); //get the current pointcount
  60632. this._points.elements.forEach(function (p) {
  60633. normals.push(0, -1.0, 0);
  60634. positions.push(p.x, -depth, p.y);
  60635. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  60636. });
  60637. var totalCount = indices.length;
  60638. for (var i = 0; i < totalCount; i += 3) {
  60639. var i0 = indices[i + 0];
  60640. var i1 = indices[i + 1];
  60641. var i2 = indices[i + 2];
  60642. indices.push(i2 + positionscount);
  60643. indices.push(i1 + positionscount);
  60644. indices.push(i0 + positionscount);
  60645. }
  60646. //Add the sides
  60647. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  60648. this._holes.forEach(function (hole) {
  60649. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  60650. });
  60651. }
  60652. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  60653. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  60654. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  60655. result.setIndices(indices);
  60656. return result;
  60657. };
  60658. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  60659. var StartIndex = positions.length / 3;
  60660. var ulength = 0;
  60661. for (var i = 0; i < points.elements.length; i++) {
  60662. var p = points.elements[i];
  60663. var p1;
  60664. if ((i + 1) > points.elements.length - 1) {
  60665. p1 = points.elements[0];
  60666. }
  60667. else {
  60668. p1 = points.elements[i + 1];
  60669. }
  60670. positions.push(p.x, 0, p.y);
  60671. positions.push(p.x, -depth, p.y);
  60672. positions.push(p1.x, 0, p1.y);
  60673. positions.push(p1.x, -depth, p1.y);
  60674. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  60675. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  60676. var v3 = v2.subtract(v1);
  60677. var v4 = new BABYLON.Vector3(0, 1, 0);
  60678. var vn = BABYLON.Vector3.Cross(v3, v4);
  60679. vn = vn.normalize();
  60680. uvs.push(ulength / bounds.width, 0);
  60681. uvs.push(ulength / bounds.width, 1);
  60682. ulength += v3.length();
  60683. uvs.push((ulength / bounds.width), 0);
  60684. uvs.push((ulength / bounds.width), 1);
  60685. if (!flip) {
  60686. normals.push(-vn.x, -vn.y, -vn.z);
  60687. normals.push(-vn.x, -vn.y, -vn.z);
  60688. normals.push(-vn.x, -vn.y, -vn.z);
  60689. normals.push(-vn.x, -vn.y, -vn.z);
  60690. indices.push(StartIndex);
  60691. indices.push(StartIndex + 1);
  60692. indices.push(StartIndex + 2);
  60693. indices.push(StartIndex + 1);
  60694. indices.push(StartIndex + 3);
  60695. indices.push(StartIndex + 2);
  60696. }
  60697. else {
  60698. normals.push(vn.x, vn.y, vn.z);
  60699. normals.push(vn.x, vn.y, vn.z);
  60700. normals.push(vn.x, vn.y, vn.z);
  60701. normals.push(vn.x, vn.y, vn.z);
  60702. indices.push(StartIndex);
  60703. indices.push(StartIndex + 2);
  60704. indices.push(StartIndex + 1);
  60705. indices.push(StartIndex + 1);
  60706. indices.push(StartIndex + 2);
  60707. indices.push(StartIndex + 3);
  60708. }
  60709. StartIndex += 4;
  60710. }
  60711. ;
  60712. };
  60713. return PolygonMeshBuilder;
  60714. }());
  60715. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  60716. })(BABYLON || (BABYLON = {}));
  60717. //# sourceMappingURL=babylon.polygonMesh.js.map
  60718. var BABYLON;
  60719. (function (BABYLON) {
  60720. // Unique ID when we import meshes from Babylon to CSG
  60721. var currentCSGMeshId = 0;
  60722. // # class Vertex
  60723. // Represents a vertex of a polygon. Use your own vertex class instead of this
  60724. // one to provide additional features like texture coordinates and vertex
  60725. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  60726. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  60727. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  60728. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  60729. // is not used anywhere else.
  60730. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  60731. var Vertex = (function () {
  60732. function Vertex(pos, normal, uv) {
  60733. this.pos = pos;
  60734. this.normal = normal;
  60735. this.uv = uv;
  60736. }
  60737. Vertex.prototype.clone = function () {
  60738. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  60739. };
  60740. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  60741. // orientation of a polygon is flipped.
  60742. Vertex.prototype.flip = function () {
  60743. this.normal = this.normal.scale(-1);
  60744. };
  60745. // Create a new vertex between this vertex and `other` by linearly
  60746. // interpolating all properties using a parameter of `t`. Subclasses should
  60747. // override this to interpolate additional properties.
  60748. Vertex.prototype.interpolate = function (other, t) {
  60749. 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));
  60750. };
  60751. return Vertex;
  60752. }());
  60753. // # class Plane
  60754. // Represents a plane in 3D space.
  60755. var Plane = (function () {
  60756. function Plane(normal, w) {
  60757. this.normal = normal;
  60758. this.w = w;
  60759. }
  60760. Plane.FromPoints = function (a, b, c) {
  60761. var v0 = c.subtract(a);
  60762. var v1 = b.subtract(a);
  60763. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  60764. return null;
  60765. }
  60766. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  60767. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  60768. };
  60769. Plane.prototype.clone = function () {
  60770. return new Plane(this.normal.clone(), this.w);
  60771. };
  60772. Plane.prototype.flip = function () {
  60773. this.normal.scaleInPlace(-1);
  60774. this.w = -this.w;
  60775. };
  60776. // Split `polygon` by this plane if needed, then put the polygon or polygon
  60777. // fragments in the appropriate lists. Coplanar polygons go into either
  60778. // `coplanarFront` or `coplanarBack` depending on their orientation with
  60779. // respect to this plane. Polygons in front or in back of this plane go into
  60780. // either `front` or `back`.
  60781. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  60782. var COPLANAR = 0;
  60783. var FRONT = 1;
  60784. var BACK = 2;
  60785. var SPANNING = 3;
  60786. // Classify each point as well as the entire polygon into one of the above
  60787. // four classes.
  60788. var polygonType = 0;
  60789. var types = [];
  60790. var i;
  60791. var t;
  60792. for (i = 0; i < polygon.vertices.length; i++) {
  60793. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  60794. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  60795. polygonType |= type;
  60796. types.push(type);
  60797. }
  60798. // Put the polygon in the correct list, splitting it when necessary.
  60799. switch (polygonType) {
  60800. case COPLANAR:
  60801. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  60802. break;
  60803. case FRONT:
  60804. front.push(polygon);
  60805. break;
  60806. case BACK:
  60807. back.push(polygon);
  60808. break;
  60809. case SPANNING:
  60810. var f = [], b = [];
  60811. for (i = 0; i < polygon.vertices.length; i++) {
  60812. var j = (i + 1) % polygon.vertices.length;
  60813. var ti = types[i], tj = types[j];
  60814. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  60815. if (ti !== BACK)
  60816. f.push(vi);
  60817. if (ti !== FRONT)
  60818. b.push(ti !== BACK ? vi.clone() : vi);
  60819. if ((ti | tj) === SPANNING) {
  60820. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  60821. var v = vi.interpolate(vj, t);
  60822. f.push(v);
  60823. b.push(v.clone());
  60824. }
  60825. }
  60826. var poly;
  60827. if (f.length >= 3) {
  60828. poly = new Polygon(f, polygon.shared);
  60829. if (poly.plane)
  60830. front.push(poly);
  60831. }
  60832. if (b.length >= 3) {
  60833. poly = new Polygon(b, polygon.shared);
  60834. if (poly.plane)
  60835. back.push(poly);
  60836. }
  60837. break;
  60838. }
  60839. };
  60840. return Plane;
  60841. }());
  60842. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  60843. // point is on the plane.
  60844. Plane.EPSILON = 1e-5;
  60845. // # class Polygon
  60846. // Represents a convex polygon. The vertices used to initialize a polygon must
  60847. // be coplanar and form a convex loop.
  60848. //
  60849. // Each convex polygon has a `shared` property, which is shared between all
  60850. // polygons that are clones of each other or were split from the same polygon.
  60851. // This can be used to define per-polygon properties (such as surface color).
  60852. var Polygon = (function () {
  60853. function Polygon(vertices, shared) {
  60854. this.vertices = vertices;
  60855. this.shared = shared;
  60856. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  60857. }
  60858. Polygon.prototype.clone = function () {
  60859. var vertices = this.vertices.map(function (v) { return v.clone(); });
  60860. return new Polygon(vertices, this.shared);
  60861. };
  60862. Polygon.prototype.flip = function () {
  60863. this.vertices.reverse().map(function (v) { v.flip(); });
  60864. this.plane.flip();
  60865. };
  60866. return Polygon;
  60867. }());
  60868. // # class Node
  60869. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  60870. // by picking a polygon to split along. That polygon (and all other coplanar
  60871. // polygons) are added directly to that node and the other polygons are added to
  60872. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  60873. // no distinction between internal and leaf nodes.
  60874. var Node = (function () {
  60875. function Node(polygons) {
  60876. this.plane = null;
  60877. this.front = null;
  60878. this.back = null;
  60879. this.polygons = [];
  60880. if (polygons) {
  60881. this.build(polygons);
  60882. }
  60883. }
  60884. Node.prototype.clone = function () {
  60885. var node = new Node();
  60886. node.plane = this.plane && this.plane.clone();
  60887. node.front = this.front && this.front.clone();
  60888. node.back = this.back && this.back.clone();
  60889. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  60890. return node;
  60891. };
  60892. // Convert solid space to empty space and empty space to solid space.
  60893. Node.prototype.invert = function () {
  60894. for (var i = 0; i < this.polygons.length; i++) {
  60895. this.polygons[i].flip();
  60896. }
  60897. if (this.plane) {
  60898. this.plane.flip();
  60899. }
  60900. if (this.front) {
  60901. this.front.invert();
  60902. }
  60903. if (this.back) {
  60904. this.back.invert();
  60905. }
  60906. var temp = this.front;
  60907. this.front = this.back;
  60908. this.back = temp;
  60909. };
  60910. // Recursively remove all polygons in `polygons` that are inside this BSP
  60911. // tree.
  60912. Node.prototype.clipPolygons = function (polygons) {
  60913. if (!this.plane)
  60914. return polygons.slice();
  60915. var front = [], back = [];
  60916. for (var i = 0; i < polygons.length; i++) {
  60917. this.plane.splitPolygon(polygons[i], front, back, front, back);
  60918. }
  60919. if (this.front) {
  60920. front = this.front.clipPolygons(front);
  60921. }
  60922. if (this.back) {
  60923. back = this.back.clipPolygons(back);
  60924. }
  60925. else {
  60926. back = [];
  60927. }
  60928. return front.concat(back);
  60929. };
  60930. // Remove all polygons in this BSP tree that are inside the other BSP tree
  60931. // `bsp`.
  60932. Node.prototype.clipTo = function (bsp) {
  60933. this.polygons = bsp.clipPolygons(this.polygons);
  60934. if (this.front)
  60935. this.front.clipTo(bsp);
  60936. if (this.back)
  60937. this.back.clipTo(bsp);
  60938. };
  60939. // Return a list of all polygons in this BSP tree.
  60940. Node.prototype.allPolygons = function () {
  60941. var polygons = this.polygons.slice();
  60942. if (this.front)
  60943. polygons = polygons.concat(this.front.allPolygons());
  60944. if (this.back)
  60945. polygons = polygons.concat(this.back.allPolygons());
  60946. return polygons;
  60947. };
  60948. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  60949. // new polygons are filtered down to the bottom of the tree and become new
  60950. // nodes there. Each set of polygons is partitioned using the first polygon
  60951. // (no heuristic is used to pick a good split).
  60952. Node.prototype.build = function (polygons) {
  60953. if (!polygons.length)
  60954. return;
  60955. if (!this.plane)
  60956. this.plane = polygons[0].plane.clone();
  60957. var front = [], back = [];
  60958. for (var i = 0; i < polygons.length; i++) {
  60959. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  60960. }
  60961. if (front.length) {
  60962. if (!this.front)
  60963. this.front = new Node();
  60964. this.front.build(front);
  60965. }
  60966. if (back.length) {
  60967. if (!this.back)
  60968. this.back = new Node();
  60969. this.back.build(back);
  60970. }
  60971. };
  60972. return Node;
  60973. }());
  60974. var CSG = (function () {
  60975. function CSG() {
  60976. this.polygons = new Array();
  60977. }
  60978. // Convert BABYLON.Mesh to BABYLON.CSG
  60979. CSG.FromMesh = function (mesh) {
  60980. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  60981. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  60982. if (mesh instanceof BABYLON.Mesh) {
  60983. mesh.computeWorldMatrix(true);
  60984. matrix = mesh.getWorldMatrix();
  60985. meshPosition = mesh.position.clone();
  60986. meshRotation = mesh.rotation.clone();
  60987. if (mesh.rotationQuaternion) {
  60988. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  60989. }
  60990. meshScaling = mesh.scaling.clone();
  60991. }
  60992. else {
  60993. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  60994. }
  60995. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60996. var subMeshes = mesh.subMeshes;
  60997. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  60998. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  60999. vertices = [];
  61000. for (var j = 0; j < 3; j++) {
  61001. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  61002. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  61003. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  61004. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  61005. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  61006. vertex = new Vertex(position, normal, uv);
  61007. vertices.push(vertex);
  61008. }
  61009. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  61010. // To handle the case of degenerated triangle
  61011. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  61012. if (polygon.plane)
  61013. polygons.push(polygon);
  61014. }
  61015. }
  61016. var csg = CSG.FromPolygons(polygons);
  61017. csg.matrix = matrix;
  61018. csg.position = meshPosition;
  61019. csg.rotation = meshRotation;
  61020. csg.scaling = meshScaling;
  61021. csg.rotationQuaternion = meshRotationQuaternion;
  61022. currentCSGMeshId++;
  61023. return csg;
  61024. };
  61025. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  61026. CSG.FromPolygons = function (polygons) {
  61027. var csg = new CSG();
  61028. csg.polygons = polygons;
  61029. return csg;
  61030. };
  61031. CSG.prototype.clone = function () {
  61032. var csg = new CSG();
  61033. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  61034. csg.copyTransformAttributes(this);
  61035. return csg;
  61036. };
  61037. CSG.prototype.toPolygons = function () {
  61038. return this.polygons;
  61039. };
  61040. CSG.prototype.union = function (csg) {
  61041. var a = new Node(this.clone().polygons);
  61042. var b = new Node(csg.clone().polygons);
  61043. a.clipTo(b);
  61044. b.clipTo(a);
  61045. b.invert();
  61046. b.clipTo(a);
  61047. b.invert();
  61048. a.build(b.allPolygons());
  61049. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  61050. };
  61051. CSG.prototype.unionInPlace = function (csg) {
  61052. var a = new Node(this.polygons);
  61053. var b = new Node(csg.polygons);
  61054. a.clipTo(b);
  61055. b.clipTo(a);
  61056. b.invert();
  61057. b.clipTo(a);
  61058. b.invert();
  61059. a.build(b.allPolygons());
  61060. this.polygons = a.allPolygons();
  61061. };
  61062. CSG.prototype.subtract = function (csg) {
  61063. var a = new Node(this.clone().polygons);
  61064. var b = new Node(csg.clone().polygons);
  61065. a.invert();
  61066. a.clipTo(b);
  61067. b.clipTo(a);
  61068. b.invert();
  61069. b.clipTo(a);
  61070. b.invert();
  61071. a.build(b.allPolygons());
  61072. a.invert();
  61073. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  61074. };
  61075. CSG.prototype.subtractInPlace = function (csg) {
  61076. var a = new Node(this.polygons);
  61077. var b = new Node(csg.polygons);
  61078. a.invert();
  61079. a.clipTo(b);
  61080. b.clipTo(a);
  61081. b.invert();
  61082. b.clipTo(a);
  61083. b.invert();
  61084. a.build(b.allPolygons());
  61085. a.invert();
  61086. this.polygons = a.allPolygons();
  61087. };
  61088. CSG.prototype.intersect = function (csg) {
  61089. var a = new Node(this.clone().polygons);
  61090. var b = new Node(csg.clone().polygons);
  61091. a.invert();
  61092. b.clipTo(a);
  61093. b.invert();
  61094. a.clipTo(b);
  61095. b.clipTo(a);
  61096. a.build(b.allPolygons());
  61097. a.invert();
  61098. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  61099. };
  61100. CSG.prototype.intersectInPlace = function (csg) {
  61101. var a = new Node(this.polygons);
  61102. var b = new Node(csg.polygons);
  61103. a.invert();
  61104. b.clipTo(a);
  61105. b.invert();
  61106. a.clipTo(b);
  61107. b.clipTo(a);
  61108. a.build(b.allPolygons());
  61109. a.invert();
  61110. this.polygons = a.allPolygons();
  61111. };
  61112. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  61113. // not modified.
  61114. CSG.prototype.inverse = function () {
  61115. var csg = this.clone();
  61116. csg.inverseInPlace();
  61117. return csg;
  61118. };
  61119. CSG.prototype.inverseInPlace = function () {
  61120. this.polygons.map(function (p) { p.flip(); });
  61121. };
  61122. // This is used to keep meshes transformations so they can be restored
  61123. // when we build back a Babylon Mesh
  61124. // NB : All CSG operations are performed in world coordinates
  61125. CSG.prototype.copyTransformAttributes = function (csg) {
  61126. this.matrix = csg.matrix;
  61127. this.position = csg.position;
  61128. this.rotation = csg.rotation;
  61129. this.scaling = csg.scaling;
  61130. this.rotationQuaternion = csg.rotationQuaternion;
  61131. return this;
  61132. };
  61133. // Build Raw mesh from CSG
  61134. // Coordinates here are in world space
  61135. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  61136. var matrix = this.matrix.clone();
  61137. matrix.invert();
  61138. 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;
  61139. if (keepSubMeshes) {
  61140. // Sort Polygons, since subMeshes are indices range
  61141. polygons.sort(function (a, b) {
  61142. if (a.shared.meshId === b.shared.meshId) {
  61143. return a.shared.subMeshId - b.shared.subMeshId;
  61144. }
  61145. else {
  61146. return a.shared.meshId - b.shared.meshId;
  61147. }
  61148. });
  61149. }
  61150. for (var i = 0, il = polygons.length; i < il; i++) {
  61151. polygon = polygons[i];
  61152. // Building SubMeshes
  61153. if (!subMesh_dict[polygon.shared.meshId]) {
  61154. subMesh_dict[polygon.shared.meshId] = {};
  61155. }
  61156. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  61157. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  61158. indexStart: +Infinity,
  61159. indexEnd: -Infinity,
  61160. materialIndex: polygon.shared.materialIndex
  61161. };
  61162. }
  61163. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  61164. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  61165. polygonIndices[0] = 0;
  61166. polygonIndices[1] = j - 1;
  61167. polygonIndices[2] = j;
  61168. for (var k = 0; k < 3; k++) {
  61169. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  61170. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  61171. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  61172. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  61173. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  61174. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  61175. // Check if 2 points can be merged
  61176. if (!(typeof vertex_idx !== 'undefined' &&
  61177. normals[vertex_idx * 3] === localNormal.x &&
  61178. normals[vertex_idx * 3 + 1] === localNormal.y &&
  61179. normals[vertex_idx * 3 + 2] === localNormal.z &&
  61180. uvs[vertex_idx * 2] === uv.x &&
  61181. uvs[vertex_idx * 2 + 1] === uv.y)) {
  61182. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  61183. uvs.push(uv.x, uv.y);
  61184. normals.push(normal.x, normal.y, normal.z);
  61185. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  61186. }
  61187. indices.push(vertex_idx);
  61188. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  61189. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  61190. currentIndex++;
  61191. }
  61192. }
  61193. }
  61194. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  61195. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  61196. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  61197. mesh.setIndices(indices);
  61198. if (keepSubMeshes) {
  61199. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  61200. var materialIndexOffset = 0, materialMaxIndex;
  61201. mesh.subMeshes = new Array();
  61202. for (var m in subMesh_dict) {
  61203. materialMaxIndex = -1;
  61204. for (var sm in subMesh_dict[m]) {
  61205. subMesh_obj = subMesh_dict[m][sm];
  61206. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  61207. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  61208. }
  61209. materialIndexOffset += ++materialMaxIndex;
  61210. }
  61211. }
  61212. return mesh;
  61213. };
  61214. // Build Mesh from CSG taking material and transforms into account
  61215. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  61216. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  61217. mesh.material = material;
  61218. mesh.position.copyFrom(this.position);
  61219. mesh.rotation.copyFrom(this.rotation);
  61220. if (this.rotationQuaternion) {
  61221. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  61222. }
  61223. mesh.scaling.copyFrom(this.scaling);
  61224. mesh.computeWorldMatrix(true);
  61225. return mesh;
  61226. };
  61227. return CSG;
  61228. }());
  61229. BABYLON.CSG = CSG;
  61230. })(BABYLON || (BABYLON = {}));
  61231. //# sourceMappingURL=babylon.csg.js.map
  61232. var BABYLON;
  61233. (function (BABYLON) {
  61234. var LensFlare = (function () {
  61235. function LensFlare(size, position, color, imgUrl, system) {
  61236. this.size = size;
  61237. this.position = position;
  61238. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  61239. this.dispose = function () {
  61240. if (this.texture) {
  61241. this.texture.dispose();
  61242. }
  61243. // Remove from scene
  61244. var index = this._system.lensFlares.indexOf(this);
  61245. this._system.lensFlares.splice(index, 1);
  61246. };
  61247. this.color = color || new BABYLON.Color3(1, 1, 1);
  61248. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  61249. this._system = system;
  61250. system.lensFlares.push(this);
  61251. }
  61252. return LensFlare;
  61253. }());
  61254. BABYLON.LensFlare = LensFlare;
  61255. })(BABYLON || (BABYLON = {}));
  61256. //# sourceMappingURL=babylon.lensFlare.js.map
  61257. var BABYLON;
  61258. (function (BABYLON) {
  61259. var LensFlareSystem = (function () {
  61260. function LensFlareSystem(name, emitter, scene) {
  61261. this.name = name;
  61262. this.lensFlares = new Array();
  61263. this.borderLimit = 300;
  61264. this.viewportBorder = 0;
  61265. this.layerMask = 0x0FFFFFFF;
  61266. this._vertexBuffers = {};
  61267. this._isEnabled = true;
  61268. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61269. this._emitter = emitter;
  61270. this.id = name;
  61271. scene.lensFlareSystems.push(this);
  61272. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  61273. var engine = scene.getEngine();
  61274. // VBO
  61275. var vertices = [];
  61276. vertices.push(1, 1);
  61277. vertices.push(-1, 1);
  61278. vertices.push(-1, -1);
  61279. vertices.push(1, -1);
  61280. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  61281. // Indices
  61282. var indices = [];
  61283. indices.push(0);
  61284. indices.push(1);
  61285. indices.push(2);
  61286. indices.push(0);
  61287. indices.push(2);
  61288. indices.push(3);
  61289. this._indexBuffer = engine.createIndexBuffer(indices);
  61290. // Effects
  61291. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  61292. }
  61293. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  61294. get: function () {
  61295. return this._isEnabled;
  61296. },
  61297. set: function (value) {
  61298. this._isEnabled = value;
  61299. },
  61300. enumerable: true,
  61301. configurable: true
  61302. });
  61303. LensFlareSystem.prototype.getScene = function () {
  61304. return this._scene;
  61305. };
  61306. LensFlareSystem.prototype.getEmitter = function () {
  61307. return this._emitter;
  61308. };
  61309. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  61310. this._emitter = newEmitter;
  61311. };
  61312. LensFlareSystem.prototype.getEmitterPosition = function () {
  61313. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  61314. };
  61315. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  61316. var position = this.getEmitterPosition();
  61317. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  61318. this._positionX = position.x;
  61319. this._positionY = position.y;
  61320. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  61321. if (this.viewportBorder > 0) {
  61322. globalViewport.x -= this.viewportBorder;
  61323. globalViewport.y -= this.viewportBorder;
  61324. globalViewport.width += this.viewportBorder * 2;
  61325. globalViewport.height += this.viewportBorder * 2;
  61326. position.x += this.viewportBorder;
  61327. position.y += this.viewportBorder;
  61328. this._positionX += this.viewportBorder;
  61329. this._positionY += this.viewportBorder;
  61330. }
  61331. if (position.z > 0) {
  61332. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  61333. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  61334. return true;
  61335. }
  61336. return true;
  61337. }
  61338. return false;
  61339. };
  61340. LensFlareSystem.prototype._isVisible = function () {
  61341. if (!this._isEnabled) {
  61342. return false;
  61343. }
  61344. var emitterPosition = this.getEmitterPosition();
  61345. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  61346. var distance = direction.length();
  61347. direction.normalize();
  61348. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  61349. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  61350. return !pickInfo.hit || pickInfo.distance > distance;
  61351. };
  61352. LensFlareSystem.prototype.render = function () {
  61353. if (!this._effect.isReady())
  61354. return false;
  61355. var engine = this._scene.getEngine();
  61356. var viewport = this._scene.activeCamera.viewport;
  61357. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  61358. // Position
  61359. if (!this.computeEffectivePosition(globalViewport)) {
  61360. return false;
  61361. }
  61362. // Visibility
  61363. if (!this._isVisible()) {
  61364. return false;
  61365. }
  61366. // Intensity
  61367. var awayX;
  61368. var awayY;
  61369. if (this._positionX < this.borderLimit + globalViewport.x) {
  61370. awayX = this.borderLimit + globalViewport.x - this._positionX;
  61371. }
  61372. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  61373. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  61374. }
  61375. else {
  61376. awayX = 0;
  61377. }
  61378. if (this._positionY < this.borderLimit + globalViewport.y) {
  61379. awayY = this.borderLimit + globalViewport.y - this._positionY;
  61380. }
  61381. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  61382. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  61383. }
  61384. else {
  61385. awayY = 0;
  61386. }
  61387. var away = (awayX > awayY) ? awayX : awayY;
  61388. away -= this.viewportBorder;
  61389. if (away > this.borderLimit) {
  61390. away = this.borderLimit;
  61391. }
  61392. var intensity = 1.0 - (away / this.borderLimit);
  61393. if (intensity < 0) {
  61394. return false;
  61395. }
  61396. if (intensity > 1.0) {
  61397. intensity = 1.0;
  61398. }
  61399. if (this.viewportBorder > 0) {
  61400. globalViewport.x += this.viewportBorder;
  61401. globalViewport.y += this.viewportBorder;
  61402. globalViewport.width -= this.viewportBorder * 2;
  61403. globalViewport.height -= this.viewportBorder * 2;
  61404. this._positionX -= this.viewportBorder;
  61405. this._positionY -= this.viewportBorder;
  61406. }
  61407. // Position
  61408. var centerX = globalViewport.x + globalViewport.width / 2;
  61409. var centerY = globalViewport.y + globalViewport.height / 2;
  61410. var distX = centerX - this._positionX;
  61411. var distY = centerY - this._positionY;
  61412. // Effects
  61413. engine.enableEffect(this._effect);
  61414. engine.setState(false);
  61415. engine.setDepthBuffer(false);
  61416. // VBOs
  61417. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  61418. // Flares
  61419. for (var index = 0; index < this.lensFlares.length; index++) {
  61420. var flare = this.lensFlares[index];
  61421. engine.setAlphaMode(flare.alphaMode);
  61422. var x = centerX - (distX * flare.position);
  61423. var y = centerY - (distY * flare.position);
  61424. var cw = flare.size;
  61425. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  61426. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  61427. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  61428. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  61429. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  61430. // Texture
  61431. this._effect.setTexture("textureSampler", flare.texture);
  61432. // Color
  61433. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  61434. // Draw order
  61435. engine.draw(true, 0, 6);
  61436. }
  61437. engine.setDepthBuffer(true);
  61438. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61439. return true;
  61440. };
  61441. LensFlareSystem.prototype.dispose = function () {
  61442. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61443. if (vertexBuffer) {
  61444. vertexBuffer.dispose();
  61445. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61446. }
  61447. if (this._indexBuffer) {
  61448. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61449. this._indexBuffer = null;
  61450. }
  61451. while (this.lensFlares.length) {
  61452. this.lensFlares[0].dispose();
  61453. }
  61454. // Remove from scene
  61455. var index = this._scene.lensFlareSystems.indexOf(this);
  61456. this._scene.lensFlareSystems.splice(index, 1);
  61457. };
  61458. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  61459. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  61460. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  61461. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  61462. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  61463. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  61464. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  61465. var parsedFlare = parsedLensFlareSystem.flares[index];
  61466. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  61467. }
  61468. return lensFlareSystem;
  61469. };
  61470. LensFlareSystem.prototype.serialize = function () {
  61471. var serializationObject = {};
  61472. serializationObject.id = this.id;
  61473. serializationObject.name = this.name;
  61474. serializationObject.emitterId = this.getEmitter().id;
  61475. serializationObject.borderLimit = this.borderLimit;
  61476. serializationObject.flares = [];
  61477. for (var index = 0; index < this.lensFlares.length; index++) {
  61478. var flare = this.lensFlares[index];
  61479. serializationObject.flares.push({
  61480. size: flare.size,
  61481. position: flare.position,
  61482. color: flare.color.asArray(),
  61483. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  61484. });
  61485. }
  61486. return serializationObject;
  61487. };
  61488. return LensFlareSystem;
  61489. }());
  61490. BABYLON.LensFlareSystem = LensFlareSystem;
  61491. })(BABYLON || (BABYLON = {}));
  61492. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  61493. var BABYLON;
  61494. (function (BABYLON) {
  61495. /**
  61496. * This is a holder class for the physics joint created by the physics plugin.
  61497. * It holds a set of functions to control the underlying joint.
  61498. */
  61499. var PhysicsJoint = (function () {
  61500. function PhysicsJoint(type, jointData) {
  61501. this.type = type;
  61502. this.jointData = jointData;
  61503. jointData.nativeParams = jointData.nativeParams || {};
  61504. }
  61505. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  61506. get: function () {
  61507. return this._physicsJoint;
  61508. },
  61509. set: function (newJoint) {
  61510. if (this._physicsJoint) {
  61511. //remove from the wolrd
  61512. }
  61513. this._physicsJoint = newJoint;
  61514. },
  61515. enumerable: true,
  61516. configurable: true
  61517. });
  61518. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  61519. set: function (physicsPlugin) {
  61520. this._physicsPlugin = physicsPlugin;
  61521. },
  61522. enumerable: true,
  61523. configurable: true
  61524. });
  61525. /**
  61526. * Execute a function that is physics-plugin specific.
  61527. * @param {Function} func the function that will be executed.
  61528. * It accepts two parameters: the physics world and the physics joint.
  61529. */
  61530. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  61531. func(this._physicsPlugin.world, this._physicsJoint);
  61532. };
  61533. return PhysicsJoint;
  61534. }());
  61535. //TODO check if the native joints are the same
  61536. //Joint Types
  61537. PhysicsJoint.DistanceJoint = 0;
  61538. PhysicsJoint.HingeJoint = 1;
  61539. PhysicsJoint.BallAndSocketJoint = 2;
  61540. PhysicsJoint.WheelJoint = 3;
  61541. PhysicsJoint.SliderJoint = 4;
  61542. //OIMO
  61543. PhysicsJoint.PrismaticJoint = 5;
  61544. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  61545. PhysicsJoint.UniversalJoint = 6;
  61546. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  61547. //Cannon
  61548. //Similar to a Ball-Joint. Different in params
  61549. PhysicsJoint.PointToPointJoint = 8;
  61550. //Cannon only at the moment
  61551. PhysicsJoint.SpringJoint = 9;
  61552. PhysicsJoint.LockJoint = 10;
  61553. BABYLON.PhysicsJoint = PhysicsJoint;
  61554. /**
  61555. * A class representing a physics distance joint.
  61556. */
  61557. var DistanceJoint = (function (_super) {
  61558. __extends(DistanceJoint, _super);
  61559. function DistanceJoint(jointData) {
  61560. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  61561. }
  61562. /**
  61563. * Update the predefined distance.
  61564. */
  61565. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  61566. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  61567. };
  61568. return DistanceJoint;
  61569. }(PhysicsJoint));
  61570. BABYLON.DistanceJoint = DistanceJoint;
  61571. var MotorEnabledJoint = (function (_super) {
  61572. __extends(MotorEnabledJoint, _super);
  61573. function MotorEnabledJoint(type, jointData) {
  61574. return _super.call(this, type, jointData) || this;
  61575. }
  61576. /**
  61577. * Set the motor values.
  61578. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61579. * @param {number} force the force to apply
  61580. * @param {number} maxForce max force for this motor.
  61581. */
  61582. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  61583. this._physicsPlugin.setMotor(this, force, maxForce);
  61584. };
  61585. /**
  61586. * Set the motor's limits.
  61587. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61588. */
  61589. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  61590. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  61591. };
  61592. return MotorEnabledJoint;
  61593. }(PhysicsJoint));
  61594. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  61595. /**
  61596. * This class represents a single hinge physics joint
  61597. */
  61598. var HingeJoint = (function (_super) {
  61599. __extends(HingeJoint, _super);
  61600. function HingeJoint(jointData) {
  61601. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  61602. }
  61603. /**
  61604. * Set the motor values.
  61605. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61606. * @param {number} force the force to apply
  61607. * @param {number} maxForce max force for this motor.
  61608. */
  61609. HingeJoint.prototype.setMotor = function (force, maxForce) {
  61610. this._physicsPlugin.setMotor(this, force, maxForce);
  61611. };
  61612. /**
  61613. * Set the motor's limits.
  61614. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61615. */
  61616. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  61617. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  61618. };
  61619. return HingeJoint;
  61620. }(MotorEnabledJoint));
  61621. BABYLON.HingeJoint = HingeJoint;
  61622. /**
  61623. * This class represents a dual hinge physics joint (same as wheel joint)
  61624. */
  61625. var Hinge2Joint = (function (_super) {
  61626. __extends(Hinge2Joint, _super);
  61627. function Hinge2Joint(jointData) {
  61628. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  61629. }
  61630. /**
  61631. * Set the motor values.
  61632. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61633. * @param {number} force the force to apply
  61634. * @param {number} maxForce max force for this motor.
  61635. * @param {motorIndex} the motor's index, 0 or 1.
  61636. */
  61637. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  61638. if (motorIndex === void 0) { motorIndex = 0; }
  61639. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  61640. };
  61641. /**
  61642. * Set the motor limits.
  61643. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61644. * @param {number} upperLimit the upper limit
  61645. * @param {number} lowerLimit lower limit
  61646. * @param {motorIndex} the motor's index, 0 or 1.
  61647. */
  61648. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  61649. if (motorIndex === void 0) { motorIndex = 0; }
  61650. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  61651. };
  61652. return Hinge2Joint;
  61653. }(MotorEnabledJoint));
  61654. BABYLON.Hinge2Joint = Hinge2Joint;
  61655. })(BABYLON || (BABYLON = {}));
  61656. //# sourceMappingURL=babylon.physicsJoint.js.map
  61657. var BABYLON;
  61658. (function (BABYLON) {
  61659. var PhysicsImpostor = (function () {
  61660. function PhysicsImpostor(object, type, _options, _scene) {
  61661. if (_options === void 0) { _options = { mass: 0 }; }
  61662. var _this = this;
  61663. this.object = object;
  61664. this.type = type;
  61665. this._options = _options;
  61666. this._scene = _scene;
  61667. this._bodyUpdateRequired = false;
  61668. this._onBeforePhysicsStepCallbacks = new Array();
  61669. this._onAfterPhysicsStepCallbacks = new Array();
  61670. this._onPhysicsCollideCallbacks = [];
  61671. this._deltaPosition = BABYLON.Vector3.Zero();
  61672. this._isDisposed = false;
  61673. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  61674. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  61675. /**
  61676. * this function is executed by the physics engine.
  61677. */
  61678. this.beforeStep = function () {
  61679. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  61680. //conjugate deltaRotation
  61681. if (_this._deltaRotationConjugated) {
  61682. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  61683. }
  61684. else {
  61685. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  61686. }
  61687. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  61688. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  61689. func(_this);
  61690. });
  61691. };
  61692. /**
  61693. * this function is executed by the physics engine.
  61694. */
  61695. this.afterStep = function () {
  61696. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  61697. func(_this);
  61698. });
  61699. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  61700. _this.object.position.addInPlace(_this._deltaPosition);
  61701. if (_this._deltaRotation) {
  61702. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  61703. }
  61704. };
  61705. /**
  61706. * Legacy collision detection event support
  61707. */
  61708. this.onCollideEvent = null;
  61709. //event and body object due to cannon's event-based architecture.
  61710. this.onCollide = function (e) {
  61711. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  61712. return;
  61713. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  61714. if (otherImpostor) {
  61715. // Legacy collision detection event support
  61716. if (_this.onCollideEvent) {
  61717. _this.onCollideEvent(_this, otherImpostor);
  61718. }
  61719. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  61720. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  61721. }).forEach(function (obj) {
  61722. obj.callback(_this, otherImpostor);
  61723. });
  61724. }
  61725. };
  61726. //sanity check!
  61727. if (!this.object) {
  61728. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  61729. return;
  61730. }
  61731. //legacy support for old syntax.
  61732. if (!this._scene && object.getScene) {
  61733. this._scene = object.getScene();
  61734. }
  61735. this._physicsEngine = this._scene.getPhysicsEngine();
  61736. if (!this._physicsEngine) {
  61737. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  61738. }
  61739. else {
  61740. //set the object's quaternion, if not set
  61741. if (!this.object.rotationQuaternion) {
  61742. if (this.object.rotation) {
  61743. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  61744. }
  61745. else {
  61746. this.object.rotationQuaternion = new BABYLON.Quaternion();
  61747. }
  61748. }
  61749. //default options params
  61750. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  61751. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  61752. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  61753. this._joints = [];
  61754. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  61755. if (!this.object.parent) {
  61756. this._init();
  61757. }
  61758. else if (this.object.parent.physicsImpostor) {
  61759. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  61760. }
  61761. }
  61762. }
  61763. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  61764. get: function () {
  61765. return this._isDisposed;
  61766. },
  61767. enumerable: true,
  61768. configurable: true
  61769. });
  61770. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  61771. get: function () {
  61772. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  61773. },
  61774. set: function (value) {
  61775. this.setMass(value);
  61776. },
  61777. enumerable: true,
  61778. configurable: true
  61779. });
  61780. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  61781. get: function () {
  61782. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  61783. },
  61784. set: function (value) {
  61785. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  61786. },
  61787. enumerable: true,
  61788. configurable: true
  61789. });
  61790. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  61791. get: function () {
  61792. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  61793. },
  61794. set: function (value) {
  61795. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  61796. },
  61797. enumerable: true,
  61798. configurable: true
  61799. });
  61800. /**
  61801. * This function will completly initialize this impostor.
  61802. * It will create a new body - but only if this mesh has no parent.
  61803. * If it has, this impostor will not be used other than to define the impostor
  61804. * of the child mesh.
  61805. */
  61806. PhysicsImpostor.prototype._init = function () {
  61807. this._physicsEngine.removeImpostor(this);
  61808. this.physicsBody = null;
  61809. this._parent = this._parent || this._getPhysicsParent();
  61810. if (!this.parent) {
  61811. this._physicsEngine.addImpostor(this);
  61812. }
  61813. };
  61814. PhysicsImpostor.prototype._getPhysicsParent = function () {
  61815. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  61816. var parentMesh = this.object.parent;
  61817. return parentMesh.physicsImpostor;
  61818. }
  61819. return;
  61820. };
  61821. /**
  61822. * Should a new body be generated.
  61823. */
  61824. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  61825. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  61826. };
  61827. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  61828. this.forceUpdate();
  61829. };
  61830. /**
  61831. * Force a regeneration of this or the parent's impostor's body.
  61832. * Use under cautious - This will remove all joints already implemented.
  61833. */
  61834. PhysicsImpostor.prototype.forceUpdate = function () {
  61835. this._init();
  61836. if (this.parent) {
  61837. this.parent.forceUpdate();
  61838. }
  61839. };
  61840. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  61841. /*public get mesh(): AbstractMesh {
  61842. return this._mesh;
  61843. }*/
  61844. /**
  61845. * Gets the body that holds this impostor. Either its own, or its parent.
  61846. */
  61847. get: function () {
  61848. return this._parent ? this._parent.physicsBody : this._physicsBody;
  61849. },
  61850. /**
  61851. * Set the physics body. Used mainly by the physics engine/plugin
  61852. */
  61853. set: function (physicsBody) {
  61854. if (this._physicsBody) {
  61855. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  61856. }
  61857. this._physicsBody = physicsBody;
  61858. this.resetUpdateFlags();
  61859. },
  61860. enumerable: true,
  61861. configurable: true
  61862. });
  61863. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  61864. get: function () {
  61865. return this._parent;
  61866. },
  61867. set: function (value) {
  61868. this._parent = value;
  61869. },
  61870. enumerable: true,
  61871. configurable: true
  61872. });
  61873. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  61874. this._bodyUpdateRequired = false;
  61875. };
  61876. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  61877. if (this.object.getBoundingInfo) {
  61878. var q = this.object.rotationQuaternion;
  61879. //reset rotation
  61880. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  61881. //calculate the world matrix with no rotation
  61882. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  61883. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  61884. //bring back the rotation
  61885. this.object.rotationQuaternion = q;
  61886. //calculate the world matrix with the new rotation
  61887. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  61888. return size;
  61889. }
  61890. else {
  61891. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  61892. }
  61893. };
  61894. PhysicsImpostor.prototype.getObjectCenter = function () {
  61895. if (this.object.getBoundingInfo) {
  61896. return this.object.getBoundingInfo().boundingBox.centerWorld;
  61897. }
  61898. else {
  61899. return this.object.position;
  61900. }
  61901. };
  61902. /**
  61903. * Get a specific parametes from the options parameter.
  61904. */
  61905. PhysicsImpostor.prototype.getParam = function (paramName) {
  61906. return this._options[paramName];
  61907. };
  61908. /**
  61909. * Sets a specific parameter in the options given to the physics plugin
  61910. */
  61911. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  61912. this._options[paramName] = value;
  61913. this._bodyUpdateRequired = true;
  61914. };
  61915. /**
  61916. * Specifically change the body's mass option. Won't recreate the physics body object
  61917. */
  61918. PhysicsImpostor.prototype.setMass = function (mass) {
  61919. if (this.getParam("mass") !== mass) {
  61920. this.setParam("mass", mass);
  61921. }
  61922. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  61923. };
  61924. PhysicsImpostor.prototype.getLinearVelocity = function () {
  61925. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  61926. };
  61927. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  61928. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  61929. };
  61930. PhysicsImpostor.prototype.getAngularVelocity = function () {
  61931. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  61932. };
  61933. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  61934. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  61935. };
  61936. /**
  61937. * Execute a function with the physics plugin native code.
  61938. * Provide a function the will have two variables - the world object and the physics body object.
  61939. */
  61940. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  61941. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  61942. };
  61943. /**
  61944. * Register a function that will be executed before the physics world is stepping forward.
  61945. */
  61946. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  61947. this._onBeforePhysicsStepCallbacks.push(func);
  61948. };
  61949. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  61950. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  61951. if (index > -1) {
  61952. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  61953. }
  61954. else {
  61955. BABYLON.Tools.Warn("Function to remove was not found");
  61956. }
  61957. };
  61958. /**
  61959. * Register a function that will be executed after the physics step
  61960. */
  61961. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  61962. this._onAfterPhysicsStepCallbacks.push(func);
  61963. };
  61964. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  61965. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  61966. if (index > -1) {
  61967. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  61968. }
  61969. else {
  61970. BABYLON.Tools.Warn("Function to remove was not found");
  61971. }
  61972. };
  61973. /**
  61974. * register a function that will be executed when this impostor collides against a different body.
  61975. */
  61976. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  61977. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  61978. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  61979. };
  61980. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  61981. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  61982. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  61983. if (index > -1) {
  61984. this._onPhysicsCollideCallbacks.splice(index, 1);
  61985. }
  61986. else {
  61987. BABYLON.Tools.Warn("Function to remove was not found");
  61988. }
  61989. };
  61990. /**
  61991. * Apply a force
  61992. */
  61993. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  61994. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  61995. };
  61996. /**
  61997. * Apply an impulse
  61998. */
  61999. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  62000. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  62001. };
  62002. /**
  62003. * A help function to create a joint.
  62004. */
  62005. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  62006. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  62007. this.addJoint(otherImpostor, joint);
  62008. };
  62009. /**
  62010. * Add a joint to this impostor with a different impostor.
  62011. */
  62012. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  62013. this._joints.push({
  62014. otherImpostor: otherImpostor,
  62015. joint: joint
  62016. });
  62017. this._physicsEngine.addJoint(this, otherImpostor, joint);
  62018. };
  62019. /**
  62020. * Will keep this body still, in a sleep mode.
  62021. */
  62022. PhysicsImpostor.prototype.sleep = function () {
  62023. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  62024. };
  62025. /**
  62026. * Wake the body up.
  62027. */
  62028. PhysicsImpostor.prototype.wakeUp = function () {
  62029. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  62030. };
  62031. PhysicsImpostor.prototype.clone = function (newObject) {
  62032. if (!newObject)
  62033. return null;
  62034. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  62035. };
  62036. PhysicsImpostor.prototype.dispose = function () {
  62037. var _this = this;
  62038. //no dispose if no physics engine is available.
  62039. if (!this._physicsEngine) {
  62040. return;
  62041. }
  62042. this._joints.forEach(function (j) {
  62043. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  62044. });
  62045. //dispose the physics body
  62046. this._physicsEngine.removeImpostor(this);
  62047. if (this.parent) {
  62048. this.parent.forceUpdate();
  62049. }
  62050. else {
  62051. /*this._object.getChildMeshes().forEach(function(mesh) {
  62052. if (mesh.physicsImpostor) {
  62053. if (disposeChildren) {
  62054. mesh.physicsImpostor.dispose();
  62055. mesh.physicsImpostor = null;
  62056. }
  62057. }
  62058. })*/
  62059. }
  62060. this._isDisposed = true;
  62061. };
  62062. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  62063. this._deltaPosition.copyFrom(position);
  62064. };
  62065. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  62066. if (!this._deltaRotation) {
  62067. this._deltaRotation = new BABYLON.Quaternion();
  62068. }
  62069. this._deltaRotation.copyFrom(rotation);
  62070. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  62071. };
  62072. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  62073. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  62074. };
  62075. PhysicsImpostor.prototype.getRadius = function () {
  62076. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  62077. };
  62078. /**
  62079. * Sync a bone with this impostor
  62080. * @param bone The bone to sync to the impostor.
  62081. * @param boneMesh The mesh that the bone is influencing.
  62082. * @param jointPivot The pivot of the joint / bone in local space.
  62083. * @param distToJoint Optional distance from the impostor to the joint.
  62084. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  62085. */
  62086. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  62087. var tempVec = PhysicsImpostor._tmpVecs[0];
  62088. var mesh = this.object;
  62089. if (adjustRotation) {
  62090. var tempQuat = PhysicsImpostor._tmpQuat;
  62091. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  62092. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  62093. }
  62094. else {
  62095. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  62096. }
  62097. tempVec.x = 0;
  62098. tempVec.y = 0;
  62099. tempVec.z = 0;
  62100. if (jointPivot) {
  62101. tempVec.x = jointPivot.x;
  62102. tempVec.y = jointPivot.y;
  62103. tempVec.z = jointPivot.z;
  62104. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  62105. if (distToJoint === undefined || distToJoint === null) {
  62106. distToJoint = jointPivot.length();
  62107. }
  62108. tempVec.x *= distToJoint;
  62109. tempVec.y *= distToJoint;
  62110. tempVec.z *= distToJoint;
  62111. }
  62112. if (bone.getParent()) {
  62113. tempVec.addInPlace(mesh.getAbsolutePosition());
  62114. bone.setAbsolutePosition(tempVec, boneMesh);
  62115. }
  62116. else {
  62117. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  62118. boneMesh.position.x -= tempVec.x;
  62119. boneMesh.position.y -= tempVec.y;
  62120. boneMesh.position.z -= tempVec.z;
  62121. }
  62122. };
  62123. /**
  62124. * Sync impostor to a bone
  62125. * @param bone The bone that the impostor will be synced to.
  62126. * @param boneMesh The mesh that the bone is influencing.
  62127. * @param jointPivot The pivot of the joint / bone in local space.
  62128. * @param distToJoint Optional distance from the impostor to the joint.
  62129. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  62130. * @param boneAxis Optional vector3 axis the bone is aligned with
  62131. */
  62132. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  62133. var mesh = this.object;
  62134. if (adjustRotation) {
  62135. var tempQuat = PhysicsImpostor._tmpQuat;
  62136. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  62137. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  62138. }
  62139. else {
  62140. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  62141. }
  62142. var pos = PhysicsImpostor._tmpVecs[0];
  62143. var boneDir = PhysicsImpostor._tmpVecs[1];
  62144. if (!boneAxis) {
  62145. boneAxis = PhysicsImpostor._tmpVecs[2];
  62146. boneAxis.x = 0;
  62147. boneAxis.y = 1;
  62148. boneAxis.z = 0;
  62149. }
  62150. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  62151. bone.getAbsolutePositionToRef(boneMesh, pos);
  62152. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  62153. distToJoint = jointPivot.length();
  62154. }
  62155. if (distToJoint !== undefined && distToJoint !== null) {
  62156. pos.x += boneDir.x * distToJoint;
  62157. pos.y += boneDir.y * distToJoint;
  62158. pos.z += boneDir.z * distToJoint;
  62159. }
  62160. mesh.setAbsolutePosition(pos);
  62161. };
  62162. return PhysicsImpostor;
  62163. }());
  62164. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  62165. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  62166. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62167. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  62168. //Impostor types
  62169. PhysicsImpostor.NoImpostor = 0;
  62170. PhysicsImpostor.SphereImpostor = 1;
  62171. PhysicsImpostor.BoxImpostor = 2;
  62172. PhysicsImpostor.PlaneImpostor = 3;
  62173. PhysicsImpostor.MeshImpostor = 4;
  62174. PhysicsImpostor.CylinderImpostor = 7;
  62175. PhysicsImpostor.ParticleImpostor = 8;
  62176. PhysicsImpostor.HeightmapImpostor = 9;
  62177. BABYLON.PhysicsImpostor = PhysicsImpostor;
  62178. })(BABYLON || (BABYLON = {}));
  62179. //# sourceMappingURL=babylon.physicsImpostor.js.map
  62180. var BABYLON;
  62181. (function (BABYLON) {
  62182. var PhysicsEngine = (function () {
  62183. function PhysicsEngine(gravity, _physicsPlugin) {
  62184. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  62185. this._physicsPlugin = _physicsPlugin;
  62186. //new methods and parameters
  62187. this._impostors = [];
  62188. this._joints = [];
  62189. if (!this._physicsPlugin.isSupported()) {
  62190. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  62191. + "Please make sure it is included.");
  62192. }
  62193. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  62194. this.setGravity(gravity);
  62195. this.setTimeStep();
  62196. }
  62197. PhysicsEngine.prototype.setGravity = function (gravity) {
  62198. this.gravity = gravity;
  62199. this._physicsPlugin.setGravity(this.gravity);
  62200. };
  62201. /**
  62202. * Set the time step of the physics engine.
  62203. * default is 1/60.
  62204. * To slow it down, enter 1/600 for example.
  62205. * To speed it up, 1/30
  62206. * @param {number} newTimeStep the new timestep to apply to this world.
  62207. */
  62208. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  62209. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  62210. this._physicsPlugin.setTimeStep(newTimeStep);
  62211. };
  62212. /**
  62213. * Get the time step of the physics engine.
  62214. */
  62215. PhysicsEngine.prototype.getTimeStep = function () {
  62216. return this._physicsPlugin.getTimeStep();
  62217. };
  62218. PhysicsEngine.prototype.dispose = function () {
  62219. this._impostors.forEach(function (impostor) {
  62220. impostor.dispose();
  62221. });
  62222. this._physicsPlugin.dispose();
  62223. };
  62224. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  62225. return this._physicsPlugin.name;
  62226. };
  62227. /**
  62228. * Adding a new impostor for the impostor tracking.
  62229. * This will be done by the impostor itself.
  62230. * @param {PhysicsImpostor} impostor the impostor to add
  62231. */
  62232. PhysicsEngine.prototype.addImpostor = function (impostor) {
  62233. impostor.uniqueId = this._impostors.push(impostor);
  62234. //if no parent, generate the body
  62235. if (!impostor.parent) {
  62236. this._physicsPlugin.generatePhysicsBody(impostor);
  62237. }
  62238. };
  62239. /**
  62240. * Remove an impostor from the engine.
  62241. * This impostor and its mesh will not longer be updated by the physics engine.
  62242. * @param {PhysicsImpostor} impostor the impostor to remove
  62243. */
  62244. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  62245. var index = this._impostors.indexOf(impostor);
  62246. if (index > -1) {
  62247. var removed = this._impostors.splice(index, 1);
  62248. //Is it needed?
  62249. if (removed.length) {
  62250. //this will also remove it from the world.
  62251. removed[0].physicsBody = null;
  62252. }
  62253. }
  62254. };
  62255. /**
  62256. * Add a joint to the physics engine
  62257. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  62258. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  62259. * @param {PhysicsJoint} the joint that will connect both impostors.
  62260. */
  62261. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  62262. var impostorJoint = {
  62263. mainImpostor: mainImpostor,
  62264. connectedImpostor: connectedImpostor,
  62265. joint: joint
  62266. };
  62267. joint.physicsPlugin = this._physicsPlugin;
  62268. this._joints.push(impostorJoint);
  62269. this._physicsPlugin.generateJoint(impostorJoint);
  62270. };
  62271. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  62272. var matchingJoints = this._joints.filter(function (impostorJoint) {
  62273. return (impostorJoint.connectedImpostor === connectedImpostor
  62274. && impostorJoint.joint === joint
  62275. && impostorJoint.mainImpostor === mainImpostor);
  62276. });
  62277. if (matchingJoints.length) {
  62278. this._physicsPlugin.removeJoint(matchingJoints[0]);
  62279. //TODO remove it from the list as well
  62280. }
  62281. };
  62282. /**
  62283. * Called by the scene. no need to call it.
  62284. */
  62285. PhysicsEngine.prototype._step = function (delta) {
  62286. var _this = this;
  62287. //check if any mesh has no body / requires an update
  62288. this._impostors.forEach(function (impostor) {
  62289. if (impostor.isBodyInitRequired()) {
  62290. _this._physicsPlugin.generatePhysicsBody(impostor);
  62291. }
  62292. });
  62293. if (delta > 0.1) {
  62294. delta = 0.1;
  62295. }
  62296. else if (delta <= 0) {
  62297. delta = 1.0 / 60.0;
  62298. }
  62299. this._physicsPlugin.executeStep(delta, this._impostors);
  62300. };
  62301. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  62302. return this._physicsPlugin;
  62303. };
  62304. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  62305. for (var i = 0; i < this._impostors.length; ++i) {
  62306. if (this._impostors[i].object === object) {
  62307. return this._impostors[i];
  62308. }
  62309. }
  62310. };
  62311. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  62312. for (var i = 0; i < this._impostors.length; ++i) {
  62313. if (this._impostors[i].physicsBody === body) {
  62314. return this._impostors[i];
  62315. }
  62316. }
  62317. };
  62318. return PhysicsEngine;
  62319. }());
  62320. // Statics
  62321. PhysicsEngine.Epsilon = 0.001;
  62322. BABYLON.PhysicsEngine = PhysicsEngine;
  62323. })(BABYLON || (BABYLON = {}));
  62324. //# sourceMappingURL=babylon.physicsEngine.js.map
  62325. var BABYLON;
  62326. (function (BABYLON) {
  62327. var CannonJSPlugin = (function () {
  62328. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  62329. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  62330. if (iterations === void 0) { iterations = 10; }
  62331. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  62332. this.name = "CannonJSPlugin";
  62333. this._physicsMaterials = [];
  62334. this._fixedTimeStep = 1 / 60;
  62335. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  62336. this._currentCollisionGroup = 2;
  62337. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  62338. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  62339. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  62340. this._tmpPosition = BABYLON.Vector3.Zero();
  62341. this._tmpQuaternion = new BABYLON.Quaternion();
  62342. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  62343. this._tmpDeltaRotation = new BABYLON.Quaternion();
  62344. this._tmpUnityRotation = new BABYLON.Quaternion();
  62345. if (!this.isSupported()) {
  62346. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  62347. return;
  62348. }
  62349. this.world = new this.BJSCANNON.World();
  62350. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  62351. this.world.solver.iterations = iterations;
  62352. }
  62353. CannonJSPlugin.prototype.setGravity = function (gravity) {
  62354. this.world.gravity.copy(gravity);
  62355. };
  62356. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  62357. this._fixedTimeStep = timeStep;
  62358. };
  62359. CannonJSPlugin.prototype.getTimeStep = function () {
  62360. return this._fixedTimeStep;
  62361. };
  62362. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  62363. // Delta is in seconds, should be provided in milliseconds
  62364. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  62365. };
  62366. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  62367. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  62368. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  62369. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  62370. };
  62371. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  62372. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  62373. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  62374. impostor.physicsBody.applyForce(impulse, worldPoint);
  62375. };
  62376. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  62377. //parent-child relationship. Does this impostor has a parent impostor?
  62378. if (impostor.parent) {
  62379. if (impostor.physicsBody) {
  62380. this.removePhysicsBody(impostor);
  62381. //TODO is that needed?
  62382. impostor.forceUpdate();
  62383. }
  62384. return;
  62385. }
  62386. //should a new body be created for this impostor?
  62387. if (impostor.isBodyInitRequired()) {
  62388. var shape = this._createShape(impostor);
  62389. //unregister events, if body is being changed
  62390. var oldBody = impostor.physicsBody;
  62391. if (oldBody) {
  62392. this.removePhysicsBody(impostor);
  62393. }
  62394. //create the body and material
  62395. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  62396. var bodyCreationObject = {
  62397. mass: impostor.getParam("mass"),
  62398. material: material
  62399. };
  62400. // A simple extend, in case native options were used.
  62401. var nativeOptions = impostor.getParam("nativeOptions");
  62402. for (var key in nativeOptions) {
  62403. if (nativeOptions.hasOwnProperty(key)) {
  62404. bodyCreationObject[key] = nativeOptions[key];
  62405. }
  62406. }
  62407. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  62408. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  62409. this.world.addEventListener("preStep", impostor.beforeStep);
  62410. this.world.addEventListener("postStep", impostor.afterStep);
  62411. impostor.physicsBody.addShape(shape);
  62412. this.world.add(impostor.physicsBody);
  62413. //try to keep the body moving in the right direction by taking old properties.
  62414. //Should be tested!
  62415. if (oldBody) {
  62416. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  62417. impostor.physicsBody[param].copy(oldBody[param]);
  62418. });
  62419. }
  62420. this._processChildMeshes(impostor);
  62421. }
  62422. //now update the body's transformation
  62423. this._updatePhysicsBodyTransformation(impostor);
  62424. };
  62425. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  62426. var _this = this;
  62427. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  62428. var currentRotation = mainImpostor.object.rotationQuaternion;
  62429. if (meshChildren.length) {
  62430. var processMesh = function (localPosition, mesh) {
  62431. var childImpostor = mesh.getPhysicsImpostor();
  62432. if (childImpostor) {
  62433. var parent = childImpostor.parent;
  62434. if (parent !== mainImpostor) {
  62435. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  62436. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  62437. if (childImpostor.physicsBody) {
  62438. _this.removePhysicsBody(childImpostor);
  62439. childImpostor.physicsBody = null;
  62440. }
  62441. childImpostor.parent = mainImpostor;
  62442. childImpostor.resetUpdateFlags();
  62443. 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));
  62444. //Add the mass of the children.
  62445. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  62446. }
  62447. }
  62448. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  62449. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  62450. };
  62451. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  62452. }
  62453. };
  62454. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  62455. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  62456. this.world.removeEventListener("preStep", impostor.beforeStep);
  62457. this.world.removeEventListener("postStep", impostor.afterStep);
  62458. this.world.remove(impostor.physicsBody);
  62459. };
  62460. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  62461. var mainBody = impostorJoint.mainImpostor.physicsBody;
  62462. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  62463. if (!mainBody || !connectedBody) {
  62464. return;
  62465. }
  62466. var constraint;
  62467. var jointData = impostorJoint.joint.jointData;
  62468. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  62469. var constraintData = {
  62470. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  62471. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  62472. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  62473. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  62474. maxForce: jointData.nativeParams.maxForce,
  62475. collideConnected: !!jointData.collision
  62476. };
  62477. switch (impostorJoint.joint.type) {
  62478. case BABYLON.PhysicsJoint.HingeJoint:
  62479. case BABYLON.PhysicsJoint.Hinge2Joint:
  62480. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  62481. break;
  62482. case BABYLON.PhysicsJoint.DistanceJoint:
  62483. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  62484. break;
  62485. case BABYLON.PhysicsJoint.SpringJoint:
  62486. var springData = jointData;
  62487. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  62488. restLength: springData.length,
  62489. stiffness: springData.stiffness,
  62490. damping: springData.damping,
  62491. localAnchorA: constraintData.pivotA,
  62492. localAnchorB: constraintData.pivotB
  62493. });
  62494. break;
  62495. case BABYLON.PhysicsJoint.LockJoint:
  62496. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  62497. break;
  62498. case BABYLON.PhysicsJoint.PointToPointJoint:
  62499. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  62500. default:
  62501. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  62502. break;
  62503. }
  62504. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  62505. constraint.collideConnected = !!jointData.collision;
  62506. impostorJoint.joint.physicsJoint = constraint;
  62507. //don't add spring as constraint, as it is not one.
  62508. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  62509. this.world.addConstraint(constraint);
  62510. }
  62511. else {
  62512. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  62513. constraint.applyForce();
  62514. });
  62515. }
  62516. };
  62517. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  62518. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  62519. };
  62520. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  62521. var index;
  62522. var mat;
  62523. for (index = 0; index < this._physicsMaterials.length; index++) {
  62524. mat = this._physicsMaterials[index];
  62525. if (mat.friction === friction && mat.restitution === restitution) {
  62526. return mat;
  62527. }
  62528. }
  62529. var currentMat = new this.BJSCANNON.Material(name);
  62530. currentMat.friction = friction;
  62531. currentMat.restitution = restitution;
  62532. this._physicsMaterials.push(currentMat);
  62533. return currentMat;
  62534. };
  62535. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  62536. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  62537. };
  62538. CannonJSPlugin.prototype._createShape = function (impostor) {
  62539. var object = impostor.object;
  62540. var returnValue;
  62541. var extendSize = impostor.getObjectExtendSize();
  62542. switch (impostor.type) {
  62543. case BABYLON.PhysicsImpostor.SphereImpostor:
  62544. var radiusX = extendSize.x;
  62545. var radiusY = extendSize.y;
  62546. var radiusZ = extendSize.z;
  62547. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  62548. break;
  62549. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  62550. case BABYLON.PhysicsImpostor.CylinderImpostor:
  62551. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  62552. break;
  62553. case BABYLON.PhysicsImpostor.BoxImpostor:
  62554. var box = extendSize.scale(0.5);
  62555. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  62556. break;
  62557. case BABYLON.PhysicsImpostor.PlaneImpostor:
  62558. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  62559. returnValue = new this.BJSCANNON.Plane();
  62560. break;
  62561. case BABYLON.PhysicsImpostor.MeshImpostor:
  62562. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  62563. var rawFaces = object.getIndices ? object.getIndices() : [];
  62564. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  62565. returnValue = new this.BJSCANNON.Trimesh(rawVerts, rawFaces);
  62566. break;
  62567. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  62568. returnValue = this._createHeightmap(object);
  62569. break;
  62570. case BABYLON.PhysicsImpostor.ParticleImpostor:
  62571. returnValue = new this.BJSCANNON.Particle();
  62572. break;
  62573. }
  62574. return returnValue;
  62575. };
  62576. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  62577. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62578. var matrix = [];
  62579. //For now pointDepth will not be used and will be automatically calculated.
  62580. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  62581. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  62582. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  62583. var elementSize = dim * 2 / arraySize;
  62584. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  62585. for (var i = 0; i < pos.length; i = i + 3) {
  62586. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  62587. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  62588. var y = pos[i + 1] + minY;
  62589. if (!matrix[x]) {
  62590. matrix[x] = [];
  62591. }
  62592. if (!matrix[x][z]) {
  62593. matrix[x][z] = y;
  62594. }
  62595. matrix[x][z] = Math.max(y, matrix[x][z]);
  62596. }
  62597. for (var x = 0; x <= arraySize; ++x) {
  62598. if (!matrix[x]) {
  62599. var loc = 1;
  62600. while (!matrix[(x + loc) % arraySize]) {
  62601. loc++;
  62602. }
  62603. matrix[x] = matrix[(x + loc) % arraySize].slice();
  62604. //console.log("missing x", x);
  62605. }
  62606. for (var z = 0; z <= arraySize; ++z) {
  62607. if (!matrix[x][z]) {
  62608. var loc = 1;
  62609. var newValue;
  62610. while (newValue === undefined) {
  62611. newValue = matrix[x][(z + loc++) % arraySize];
  62612. }
  62613. matrix[x][z] = newValue;
  62614. }
  62615. }
  62616. }
  62617. var shape = new this.BJSCANNON.Heightfield(matrix, {
  62618. elementSize: elementSize
  62619. });
  62620. //For future reference, needed for body transformation
  62621. shape.minY = minY;
  62622. return shape;
  62623. };
  62624. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  62625. var object = impostor.object;
  62626. //make sure it is updated...
  62627. object.computeWorldMatrix && object.computeWorldMatrix(true);
  62628. // The delta between the mesh position and the mesh bounding box center
  62629. var center = impostor.getObjectCenter();
  62630. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  62631. this._tmpPosition.copyFrom(center);
  62632. var quaternion = object.rotationQuaternion;
  62633. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  62634. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  62635. //-90 DEG in X, precalculated
  62636. quaternion = quaternion.multiply(this._minus90X);
  62637. //Invert! (Precalculated, 90 deg in X)
  62638. //No need to clone. this will never change.
  62639. impostor.setDeltaRotation(this._plus90X);
  62640. }
  62641. //If it is a heightfield, if should be centered.
  62642. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  62643. var mesh = object;
  62644. //calculate the correct body position:
  62645. var rotationQuaternion = mesh.rotationQuaternion;
  62646. mesh.rotationQuaternion = this._tmpUnityRotation;
  62647. mesh.computeWorldMatrix(true);
  62648. //get original center with no rotation
  62649. var c = center.clone();
  62650. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  62651. //rotation is back
  62652. mesh.rotationQuaternion = rotationQuaternion;
  62653. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  62654. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  62655. mesh.setPivotMatrix(p);
  62656. mesh.computeWorldMatrix(true);
  62657. //calculate the translation
  62658. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  62659. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  62660. //add it inverted to the delta
  62661. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  62662. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  62663. mesh.setPivotMatrix(oldPivot);
  62664. mesh.computeWorldMatrix(true);
  62665. }
  62666. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  62667. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  62668. this._tmpPosition.copyFrom(object.position);
  62669. }
  62670. impostor.setDeltaPosition(this._tmpDeltaPosition);
  62671. //Now update the impostor object
  62672. impostor.physicsBody.position.copy(this._tmpPosition);
  62673. impostor.physicsBody.quaternion.copy(quaternion);
  62674. };
  62675. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  62676. impostor.object.position.copyFrom(impostor.physicsBody.position);
  62677. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  62678. };
  62679. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  62680. impostor.physicsBody.position.copy(newPosition);
  62681. impostor.physicsBody.quaternion.copy(newRotation);
  62682. };
  62683. CannonJSPlugin.prototype.isSupported = function () {
  62684. return this.BJSCANNON !== undefined;
  62685. };
  62686. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  62687. impostor.physicsBody.velocity.copy(velocity);
  62688. };
  62689. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  62690. impostor.physicsBody.angularVelocity.copy(velocity);
  62691. };
  62692. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  62693. var v = impostor.physicsBody.velocity;
  62694. if (!v)
  62695. return null;
  62696. return new BABYLON.Vector3(v.x, v.y, v.z);
  62697. };
  62698. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  62699. var v = impostor.physicsBody.angularVelocity;
  62700. if (!v)
  62701. return null;
  62702. return new BABYLON.Vector3(v.x, v.y, v.z);
  62703. };
  62704. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  62705. impostor.physicsBody.mass = mass;
  62706. impostor.physicsBody.updateMassProperties();
  62707. };
  62708. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  62709. return impostor.physicsBody.mass;
  62710. };
  62711. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  62712. return impostor.physicsBody.material.friction;
  62713. };
  62714. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  62715. impostor.physicsBody.material.friction = friction;
  62716. };
  62717. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  62718. return impostor.physicsBody.material.restitution;
  62719. };
  62720. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  62721. impostor.physicsBody.material.restitution = restitution;
  62722. };
  62723. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  62724. impostor.physicsBody.sleep();
  62725. };
  62726. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  62727. impostor.physicsBody.wakeUp();
  62728. };
  62729. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  62730. joint.physicsJoint.distance = maxDistance;
  62731. };
  62732. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  62733. if (!motorIndex) {
  62734. joint.physicsJoint.enableMotor();
  62735. }
  62736. };
  62737. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  62738. if (!motorIndex) {
  62739. joint.physicsJoint.disableMotor();
  62740. }
  62741. };
  62742. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  62743. if (!motorIndex) {
  62744. joint.physicsJoint.enableMotor();
  62745. joint.physicsJoint.setMotorSpeed(speed);
  62746. if (maxForce) {
  62747. this.setLimit(joint, maxForce);
  62748. }
  62749. }
  62750. };
  62751. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  62752. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  62753. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  62754. };
  62755. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  62756. var body = impostor.physicsBody;
  62757. mesh.position.x = body.position.x;
  62758. mesh.position.y = body.position.y;
  62759. mesh.position.z = body.position.z;
  62760. mesh.rotationQuaternion.x = body.quaternion.x;
  62761. mesh.rotationQuaternion.y = body.quaternion.y;
  62762. mesh.rotationQuaternion.z = body.quaternion.z;
  62763. mesh.rotationQuaternion.w = body.quaternion.w;
  62764. };
  62765. CannonJSPlugin.prototype.getRadius = function (impostor) {
  62766. var shape = impostor.physicsBody.shapes[0];
  62767. return shape.boundingSphereRadius;
  62768. };
  62769. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  62770. var shape = impostor.physicsBody.shapes[0];
  62771. result.x = shape.halfExtents.x * 2;
  62772. result.y = shape.halfExtents.y * 2;
  62773. result.z = shape.halfExtents.z * 2;
  62774. };
  62775. CannonJSPlugin.prototype.dispose = function () {
  62776. };
  62777. return CannonJSPlugin;
  62778. }());
  62779. BABYLON.CannonJSPlugin = CannonJSPlugin;
  62780. })(BABYLON || (BABYLON = {}));
  62781. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  62782. var BABYLON;
  62783. (function (BABYLON) {
  62784. var OimoJSPlugin = (function () {
  62785. function OimoJSPlugin(iterations) {
  62786. this.name = "OimoJSPlugin";
  62787. this._tmpImpostorsArray = [];
  62788. this._tmpPositionVector = BABYLON.Vector3.Zero();
  62789. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  62790. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  62791. this.world.worldscale(1);
  62792. this.world.clear();
  62793. //making sure no stats are calculated
  62794. this.world.isNoStat = true;
  62795. }
  62796. OimoJSPlugin.prototype.setGravity = function (gravity) {
  62797. this.world.gravity.copy(gravity);
  62798. };
  62799. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  62800. this.world.timeStep = timeStep;
  62801. };
  62802. OimoJSPlugin.prototype.getTimeStep = function () {
  62803. return this.world.timeStep;
  62804. };
  62805. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  62806. var _this = this;
  62807. impostors.forEach(function (impostor) {
  62808. impostor.beforeStep();
  62809. });
  62810. this.world.step();
  62811. impostors.forEach(function (impostor) {
  62812. impostor.afterStep();
  62813. //update the ordered impostors array
  62814. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  62815. });
  62816. //check for collisions
  62817. var contact = this.world.contacts;
  62818. while (contact !== null) {
  62819. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  62820. contact = contact.next;
  62821. continue;
  62822. }
  62823. //is this body colliding with any other? get the impostor
  62824. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  62825. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  62826. if (!mainImpostor || !collidingImpostor) {
  62827. contact = contact.next;
  62828. continue;
  62829. }
  62830. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  62831. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  62832. contact = contact.next;
  62833. }
  62834. };
  62835. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  62836. var mass = impostor.physicsBody.massInfo.mass;
  62837. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  62838. };
  62839. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  62840. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  62841. this.applyImpulse(impostor, force, contactPoint);
  62842. };
  62843. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  62844. var _this = this;
  62845. //parent-child relationship. Does this impostor has a parent impostor?
  62846. if (impostor.parent) {
  62847. if (impostor.physicsBody) {
  62848. this.removePhysicsBody(impostor);
  62849. //TODO is that needed?
  62850. impostor.forceUpdate();
  62851. }
  62852. return;
  62853. }
  62854. if (impostor.isBodyInitRequired()) {
  62855. var bodyConfig = {
  62856. name: impostor.uniqueId,
  62857. //Oimo must have mass, also for static objects.
  62858. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  62859. size: [],
  62860. type: [],
  62861. pos: [],
  62862. rot: [],
  62863. move: impostor.getParam("mass") !== 0,
  62864. //Supporting older versions of Oimo
  62865. world: this.world
  62866. };
  62867. var impostors = [impostor];
  62868. var addToArray = function (parent) {
  62869. if (!parent.getChildMeshes)
  62870. return;
  62871. parent.getChildMeshes().forEach(function (m) {
  62872. if (m.physicsImpostor) {
  62873. impostors.push(m.physicsImpostor);
  62874. //m.physicsImpostor._init();
  62875. }
  62876. });
  62877. };
  62878. addToArray(impostor.object);
  62879. var checkWithEpsilon_1 = function (value) {
  62880. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  62881. };
  62882. impostors.forEach(function (i) {
  62883. //get the correct bounding box
  62884. var oldQuaternion = i.object.rotationQuaternion;
  62885. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  62886. x: impostor.object.rotationQuaternion.x,
  62887. y: impostor.object.rotationQuaternion.y,
  62888. z: impostor.object.rotationQuaternion.z,
  62889. s: impostor.object.rotationQuaternion.w
  62890. });
  62891. var extendSize = i.getObjectExtendSize();
  62892. if (i === impostor) {
  62893. var center = impostor.getObjectCenter();
  62894. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  62895. //Can also use Array.prototype.push.apply
  62896. bodyConfig.pos.push(center.x);
  62897. bodyConfig.pos.push(center.y);
  62898. bodyConfig.pos.push(center.z);
  62899. //tmp solution
  62900. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  62901. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  62902. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  62903. }
  62904. else {
  62905. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  62906. bodyConfig.pos.push(localPosition.x);
  62907. bodyConfig.pos.push(localPosition.y);
  62908. bodyConfig.pos.push(localPosition.z);
  62909. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  62910. bodyConfig.rot.push(0);
  62911. bodyConfig.rot.push(0);
  62912. bodyConfig.rot.push(0);
  62913. }
  62914. // register mesh
  62915. switch (i.type) {
  62916. case BABYLON.PhysicsImpostor.ParticleImpostor:
  62917. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  62918. case BABYLON.PhysicsImpostor.SphereImpostor:
  62919. var radiusX = extendSize.x;
  62920. var radiusY = extendSize.y;
  62921. var radiusZ = extendSize.z;
  62922. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  62923. bodyConfig.type.push('sphere');
  62924. //due to the way oimo works with compounds, add 3 times
  62925. bodyConfig.size.push(size);
  62926. bodyConfig.size.push(size);
  62927. bodyConfig.size.push(size);
  62928. break;
  62929. case BABYLON.PhysicsImpostor.CylinderImpostor:
  62930. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  62931. var sizeY = checkWithEpsilon_1(extendSize.y);
  62932. bodyConfig.type.push('cylinder');
  62933. bodyConfig.size.push(sizeX);
  62934. bodyConfig.size.push(sizeY);
  62935. //due to the way oimo works with compounds, add one more value.
  62936. bodyConfig.size.push(sizeY);
  62937. break;
  62938. case BABYLON.PhysicsImpostor.PlaneImpostor:
  62939. case BABYLON.PhysicsImpostor.BoxImpostor:
  62940. default:
  62941. var sizeX = checkWithEpsilon_1(extendSize.x);
  62942. var sizeY = checkWithEpsilon_1(extendSize.y);
  62943. var sizeZ = checkWithEpsilon_1(extendSize.z);
  62944. bodyConfig.type.push('box');
  62945. bodyConfig.size.push(sizeX);
  62946. bodyConfig.size.push(sizeY);
  62947. bodyConfig.size.push(sizeZ);
  62948. break;
  62949. }
  62950. //actually not needed, but hey...
  62951. i.object.rotationQuaternion = oldQuaternion;
  62952. });
  62953. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  62954. }
  62955. else {
  62956. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  62957. }
  62958. impostor.setDeltaPosition(this._tmpPositionVector);
  62959. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  62960. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  62961. };
  62962. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  62963. //impostor.physicsBody.dispose();
  62964. //Same as : (older oimo versions)
  62965. this.world.removeRigidBody(impostor.physicsBody);
  62966. };
  62967. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  62968. var mainBody = impostorJoint.mainImpostor.physicsBody;
  62969. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  62970. if (!mainBody || !connectedBody) {
  62971. return;
  62972. }
  62973. var jointData = impostorJoint.joint.jointData;
  62974. var options = jointData.nativeParams || {};
  62975. var type;
  62976. var nativeJointData = {
  62977. body1: mainBody,
  62978. body2: connectedBody,
  62979. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  62980. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  62981. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  62982. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  62983. min: options.min,
  62984. max: options.max,
  62985. collision: options.collision || jointData.collision,
  62986. spring: options.spring,
  62987. //supporting older version of Oimo
  62988. world: this.world
  62989. };
  62990. switch (impostorJoint.joint.type) {
  62991. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  62992. type = "jointBall";
  62993. break;
  62994. case BABYLON.PhysicsJoint.SpringJoint:
  62995. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  62996. var springData = jointData;
  62997. nativeJointData.min = springData.length || nativeJointData.min;
  62998. //Max should also be set, just make sure it is at least min
  62999. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  63000. case BABYLON.PhysicsJoint.DistanceJoint:
  63001. type = "jointDistance";
  63002. nativeJointData.max = jointData.maxDistance;
  63003. break;
  63004. case BABYLON.PhysicsJoint.PrismaticJoint:
  63005. type = "jointPrisme";
  63006. break;
  63007. case BABYLON.PhysicsJoint.SliderJoint:
  63008. type = "jointSlide";
  63009. break;
  63010. case BABYLON.PhysicsJoint.WheelJoint:
  63011. type = "jointWheel";
  63012. break;
  63013. case BABYLON.PhysicsJoint.HingeJoint:
  63014. default:
  63015. type = "jointHinge";
  63016. break;
  63017. }
  63018. nativeJointData.type = type;
  63019. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  63020. };
  63021. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  63022. //Bug in Oimo prevents us from disposing a joint in the playground
  63023. //joint.joint.physicsJoint.dispose();
  63024. //So we will bruteforce it!
  63025. try {
  63026. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  63027. }
  63028. catch (e) {
  63029. BABYLON.Tools.Warn(e);
  63030. }
  63031. };
  63032. OimoJSPlugin.prototype.isSupported = function () {
  63033. return this.BJSOIMO !== undefined;
  63034. };
  63035. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  63036. if (!impostor.physicsBody.sleeping) {
  63037. //TODO check that
  63038. if (impostor.physicsBody.shapes.next) {
  63039. var parentShape = this._getLastShape(impostor.physicsBody);
  63040. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  63041. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  63042. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  63043. }
  63044. else {
  63045. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  63046. }
  63047. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  63048. impostor.object.rotationQuaternion.normalize();
  63049. }
  63050. };
  63051. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  63052. var body = impostor.physicsBody;
  63053. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  63054. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  63055. body.syncShapes();
  63056. body.awake();
  63057. };
  63058. OimoJSPlugin.prototype._getLastShape = function (body) {
  63059. var lastShape = body.shapes;
  63060. while (lastShape.next) {
  63061. lastShape = lastShape.next;
  63062. }
  63063. return lastShape;
  63064. };
  63065. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  63066. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  63067. };
  63068. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  63069. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  63070. };
  63071. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  63072. var v = impostor.physicsBody.linearVelocity;
  63073. if (!v)
  63074. return null;
  63075. return new BABYLON.Vector3(v.x, v.y, v.z);
  63076. };
  63077. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  63078. var v = impostor.physicsBody.angularVelocity;
  63079. if (!v)
  63080. return null;
  63081. return new BABYLON.Vector3(v.x, v.y, v.z);
  63082. };
  63083. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  63084. var staticBody = mass === 0;
  63085. //this will actually set the body's density and not its mass.
  63086. //But this is how oimo treats the mass variable.
  63087. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  63088. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  63089. };
  63090. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  63091. return impostor.physicsBody.shapes.density;
  63092. };
  63093. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  63094. return impostor.physicsBody.shapes.friction;
  63095. };
  63096. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  63097. impostor.physicsBody.shapes.friction = friction;
  63098. };
  63099. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  63100. return impostor.physicsBody.shapes.restitution;
  63101. };
  63102. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  63103. impostor.physicsBody.shapes.restitution = restitution;
  63104. };
  63105. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  63106. impostor.physicsBody.sleep();
  63107. };
  63108. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  63109. impostor.physicsBody.awake();
  63110. };
  63111. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  63112. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  63113. if (minDistance !== void 0) {
  63114. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  63115. }
  63116. };
  63117. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  63118. //TODO separate rotational and transational motors.
  63119. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  63120. if (motor) {
  63121. motor.setMotor(speed, maxForce);
  63122. }
  63123. };
  63124. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  63125. //TODO separate rotational and transational motors.
  63126. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  63127. if (motor) {
  63128. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  63129. }
  63130. };
  63131. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  63132. var body = impostor.physicsBody;
  63133. mesh.position.x = body.position.x;
  63134. mesh.position.y = body.position.y;
  63135. mesh.position.z = body.position.z;
  63136. mesh.rotationQuaternion.x = body.orientation.x;
  63137. mesh.rotationQuaternion.y = body.orientation.y;
  63138. mesh.rotationQuaternion.z = body.orientation.z;
  63139. mesh.rotationQuaternion.w = body.orientation.s;
  63140. };
  63141. OimoJSPlugin.prototype.getRadius = function (impostor) {
  63142. return impostor.physicsBody.shapes.radius;
  63143. };
  63144. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  63145. var shape = impostor.physicsBody.shapes;
  63146. result.x = shape.halfWidth * 2;
  63147. result.y = shape.halfHeight * 2;
  63148. result.z = shape.halfDepth * 2;
  63149. };
  63150. OimoJSPlugin.prototype.dispose = function () {
  63151. this.world.clear();
  63152. };
  63153. return OimoJSPlugin;
  63154. }());
  63155. BABYLON.OimoJSPlugin = OimoJSPlugin;
  63156. })(BABYLON || (BABYLON = {}));
  63157. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  63158. var BABYLON;
  63159. (function (BABYLON) {
  63160. var Internals;
  63161. (function (Internals) {
  63162. /*
  63163. * Based on jsTGALoader - Javascript loader for TGA file
  63164. * By Vincent Thibault
  63165. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  63166. */
  63167. var TGATools = (function () {
  63168. function TGATools() {
  63169. }
  63170. TGATools.GetTGAHeader = function (data) {
  63171. var offset = 0;
  63172. var header = {
  63173. id_length: data[offset++],
  63174. colormap_type: data[offset++],
  63175. image_type: data[offset++],
  63176. colormap_index: data[offset++] | data[offset++] << 8,
  63177. colormap_length: data[offset++] | data[offset++] << 8,
  63178. colormap_size: data[offset++],
  63179. origin: [
  63180. data[offset++] | data[offset++] << 8,
  63181. data[offset++] | data[offset++] << 8
  63182. ],
  63183. width: data[offset++] | data[offset++] << 8,
  63184. height: data[offset++] | data[offset++] << 8,
  63185. pixel_size: data[offset++],
  63186. flags: data[offset++]
  63187. };
  63188. return header;
  63189. };
  63190. TGATools.UploadContent = function (gl, data) {
  63191. // Not enough data to contain header ?
  63192. if (data.length < 19) {
  63193. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  63194. return;
  63195. }
  63196. // Read Header
  63197. var offset = 18;
  63198. var header = TGATools.GetTGAHeader(data);
  63199. // Assume it's a valid Targa file.
  63200. if (header.id_length + offset > data.length) {
  63201. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  63202. return;
  63203. }
  63204. // Skip not needed data
  63205. offset += header.id_length;
  63206. var use_rle = false;
  63207. var use_pal = false;
  63208. var use_rgb = false;
  63209. var use_grey = false;
  63210. // Get some informations.
  63211. switch (header.image_type) {
  63212. case TGATools._TYPE_RLE_INDEXED:
  63213. use_rle = true;
  63214. case TGATools._TYPE_INDEXED:
  63215. use_pal = true;
  63216. break;
  63217. case TGATools._TYPE_RLE_RGB:
  63218. use_rle = true;
  63219. case TGATools._TYPE_RGB:
  63220. use_rgb = true;
  63221. break;
  63222. case TGATools._TYPE_RLE_GREY:
  63223. use_rle = true;
  63224. case TGATools._TYPE_GREY:
  63225. use_grey = true;
  63226. break;
  63227. }
  63228. var pixel_data;
  63229. var numAlphaBits = header.flags & 0xf;
  63230. var pixel_size = header.pixel_size >> 3;
  63231. var pixel_total = header.width * header.height * pixel_size;
  63232. // Read palettes
  63233. var palettes;
  63234. if (use_pal) {
  63235. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  63236. }
  63237. // Read LRE
  63238. if (use_rle) {
  63239. pixel_data = new Uint8Array(pixel_total);
  63240. var c, count, i;
  63241. var localOffset = 0;
  63242. var pixels = new Uint8Array(pixel_size);
  63243. while (offset < pixel_total && localOffset < pixel_total) {
  63244. c = data[offset++];
  63245. count = (c & 0x7f) + 1;
  63246. // RLE pixels
  63247. if (c & 0x80) {
  63248. // Bind pixel tmp array
  63249. for (i = 0; i < pixel_size; ++i) {
  63250. pixels[i] = data[offset++];
  63251. }
  63252. // Copy pixel array
  63253. for (i = 0; i < count; ++i) {
  63254. pixel_data.set(pixels, localOffset + i * pixel_size);
  63255. }
  63256. localOffset += pixel_size * count;
  63257. }
  63258. else {
  63259. count *= pixel_size;
  63260. for (i = 0; i < count; ++i) {
  63261. pixel_data[localOffset + i] = data[offset++];
  63262. }
  63263. localOffset += count;
  63264. }
  63265. }
  63266. }
  63267. else {
  63268. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  63269. }
  63270. // Load to texture
  63271. var x_start, y_start, x_step, y_step, y_end, x_end;
  63272. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  63273. default:
  63274. case TGATools._ORIGIN_UL:
  63275. x_start = 0;
  63276. x_step = 1;
  63277. x_end = header.width;
  63278. y_start = 0;
  63279. y_step = 1;
  63280. y_end = header.height;
  63281. break;
  63282. case TGATools._ORIGIN_BL:
  63283. x_start = 0;
  63284. x_step = 1;
  63285. x_end = header.width;
  63286. y_start = header.height - 1;
  63287. y_step = -1;
  63288. y_end = -1;
  63289. break;
  63290. case TGATools._ORIGIN_UR:
  63291. x_start = header.width - 1;
  63292. x_step = -1;
  63293. x_end = -1;
  63294. y_start = 0;
  63295. y_step = 1;
  63296. y_end = header.height;
  63297. break;
  63298. case TGATools._ORIGIN_BR:
  63299. x_start = header.width - 1;
  63300. x_step = -1;
  63301. x_end = -1;
  63302. y_start = header.height - 1;
  63303. y_step = -1;
  63304. y_end = -1;
  63305. break;
  63306. }
  63307. // Load the specify method
  63308. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  63309. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  63310. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  63311. };
  63312. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63313. var image = pixel_data, colormap = palettes;
  63314. var width = header.width, height = header.height;
  63315. var color, i = 0, x, y;
  63316. var imageData = new Uint8Array(width * height * 4);
  63317. for (y = y_start; y !== y_end; y += y_step) {
  63318. for (x = x_start; x !== x_end; x += x_step, i++) {
  63319. color = image[i];
  63320. imageData[(x + width * y) * 4 + 3] = 255;
  63321. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  63322. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  63323. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  63324. }
  63325. }
  63326. return imageData;
  63327. };
  63328. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63329. var image = pixel_data;
  63330. var width = header.width, height = header.height;
  63331. var color, i = 0, x, y;
  63332. var imageData = new Uint8Array(width * height * 4);
  63333. for (y = y_start; y !== y_end; y += y_step) {
  63334. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  63335. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  63336. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  63337. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  63338. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  63339. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  63340. }
  63341. }
  63342. return imageData;
  63343. };
  63344. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63345. var image = pixel_data;
  63346. var width = header.width, height = header.height;
  63347. var i = 0, x, y;
  63348. var imageData = new Uint8Array(width * height * 4);
  63349. for (y = y_start; y !== y_end; y += y_step) {
  63350. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  63351. imageData[(x + width * y) * 4 + 3] = 255;
  63352. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  63353. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  63354. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  63355. }
  63356. }
  63357. return imageData;
  63358. };
  63359. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63360. var image = pixel_data;
  63361. var width = header.width, height = header.height;
  63362. var i = 0, x, y;
  63363. var imageData = new Uint8Array(width * height * 4);
  63364. for (y = y_start; y !== y_end; y += y_step) {
  63365. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  63366. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  63367. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  63368. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  63369. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  63370. }
  63371. }
  63372. return imageData;
  63373. };
  63374. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63375. var image = pixel_data;
  63376. var width = header.width, height = header.height;
  63377. var color, i = 0, x, y;
  63378. var imageData = new Uint8Array(width * height * 4);
  63379. for (y = y_start; y !== y_end; y += y_step) {
  63380. for (x = x_start; x !== x_end; x += x_step, i++) {
  63381. color = image[i];
  63382. imageData[(x + width * y) * 4 + 0] = color;
  63383. imageData[(x + width * y) * 4 + 1] = color;
  63384. imageData[(x + width * y) * 4 + 2] = color;
  63385. imageData[(x + width * y) * 4 + 3] = 255;
  63386. }
  63387. }
  63388. return imageData;
  63389. };
  63390. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63391. var image = pixel_data;
  63392. var width = header.width, height = header.height;
  63393. var i = 0, x, y;
  63394. var imageData = new Uint8Array(width * height * 4);
  63395. for (y = y_start; y !== y_end; y += y_step) {
  63396. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  63397. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  63398. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  63399. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  63400. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  63401. }
  63402. }
  63403. return imageData;
  63404. };
  63405. return TGATools;
  63406. }());
  63407. TGATools._TYPE_NO_DATA = 0;
  63408. TGATools._TYPE_INDEXED = 1;
  63409. TGATools._TYPE_RGB = 2;
  63410. TGATools._TYPE_GREY = 3;
  63411. TGATools._TYPE_RLE_INDEXED = 9;
  63412. TGATools._TYPE_RLE_RGB = 10;
  63413. TGATools._TYPE_RLE_GREY = 11;
  63414. TGATools._ORIGIN_MASK = 0x30;
  63415. TGATools._ORIGIN_SHIFT = 0x04;
  63416. TGATools._ORIGIN_BL = 0x00;
  63417. TGATools._ORIGIN_BR = 0x01;
  63418. TGATools._ORIGIN_UL = 0x02;
  63419. TGATools._ORIGIN_UR = 0x03;
  63420. Internals.TGATools = TGATools;
  63421. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63422. })(BABYLON || (BABYLON = {}));
  63423. //# sourceMappingURL=babylon.tga.js.map
  63424. var BABYLON;
  63425. (function (BABYLON) {
  63426. var Internals;
  63427. (function (Internals) {
  63428. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  63429. // All values and structures referenced from:
  63430. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  63431. var DDS_MAGIC = 0x20534444;
  63432. 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;
  63433. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  63434. 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;
  63435. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  63436. function FourCCToInt32(value) {
  63437. return value.charCodeAt(0) +
  63438. (value.charCodeAt(1) << 8) +
  63439. (value.charCodeAt(2) << 16) +
  63440. (value.charCodeAt(3) << 24);
  63441. }
  63442. function Int32ToFourCC(value) {
  63443. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  63444. }
  63445. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  63446. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  63447. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  63448. var FOURCC_DX10 = FourCCToInt32("DX10");
  63449. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  63450. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  63451. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  63452. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  63453. var headerLengthInt = 31; // The header length in 32 bit ints
  63454. // Offsets into the header array
  63455. var off_magic = 0;
  63456. var off_size = 1;
  63457. var off_flags = 2;
  63458. var off_height = 3;
  63459. var off_width = 4;
  63460. var off_mipmapCount = 7;
  63461. var off_pfFlags = 20;
  63462. var off_pfFourCC = 21;
  63463. var off_RGBbpp = 22;
  63464. var off_RMask = 23;
  63465. var off_GMask = 24;
  63466. var off_BMask = 25;
  63467. var off_AMask = 26;
  63468. var off_caps1 = 27;
  63469. var off_caps2 = 28;
  63470. var off_caps3 = 29;
  63471. var off_caps4 = 30;
  63472. var off_dxgiFormat = 32;
  63473. ;
  63474. var DDSTools = (function () {
  63475. function DDSTools() {
  63476. }
  63477. DDSTools.GetDDSInfo = function (arrayBuffer) {
  63478. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  63479. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  63480. var mipmapCount = 1;
  63481. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  63482. mipmapCount = Math.max(1, header[off_mipmapCount]);
  63483. }
  63484. var fourCC = header[off_pfFourCC];
  63485. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  63486. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63487. switch (fourCC) {
  63488. case FOURCC_D3DFMT_R16G16B16A16F:
  63489. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63490. break;
  63491. case FOURCC_D3DFMT_R32G32B32A32F:
  63492. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63493. break;
  63494. case FOURCC_DX10:
  63495. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  63496. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63497. break;
  63498. }
  63499. }
  63500. return {
  63501. width: header[off_width],
  63502. height: header[off_height],
  63503. mipmapCount: mipmapCount,
  63504. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  63505. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  63506. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  63507. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  63508. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  63509. dxgiFormat: dxgiFormat,
  63510. textureType: textureType
  63511. };
  63512. };
  63513. DDSTools._ToHalfFloat = function (value) {
  63514. if (!DDSTools._FloatView) {
  63515. DDSTools._FloatView = new Float32Array(1);
  63516. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  63517. }
  63518. DDSTools._FloatView[0] = value;
  63519. var x = DDSTools._Int32View[0];
  63520. var bits = (x >> 16) & 0x8000; /* Get the sign */
  63521. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  63522. var e = (x >> 23) & 0xff; /* Using int is faster here */
  63523. /* If zero, or denormal, or exponent underflows too much for a denormal
  63524. * half, return signed zero. */
  63525. if (e < 103) {
  63526. return bits;
  63527. }
  63528. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  63529. if (e > 142) {
  63530. bits |= 0x7c00;
  63531. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  63532. * not Inf, so make sure we set one mantissa bit too. */
  63533. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  63534. return bits;
  63535. }
  63536. /* If exponent underflows but not too much, return a denormal */
  63537. if (e < 113) {
  63538. m |= 0x0800;
  63539. /* Extra rounding may overflow and set mantissa to 0 and exponent
  63540. * to 1, which is OK. */
  63541. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  63542. return bits;
  63543. }
  63544. bits |= ((e - 112) << 10) | (m >> 1);
  63545. bits += m & 1;
  63546. return bits;
  63547. };
  63548. DDSTools._FromHalfFloat = function (value) {
  63549. var s = (value & 0x8000) >> 15;
  63550. var e = (value & 0x7C00) >> 10;
  63551. var f = value & 0x03FF;
  63552. if (e === 0) {
  63553. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  63554. }
  63555. else if (e == 0x1F) {
  63556. return f ? NaN : ((s ? -1 : 1) * Infinity);
  63557. }
  63558. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  63559. };
  63560. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63561. var destArray = new Float32Array(dataLength);
  63562. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  63563. var index = 0;
  63564. for (var y = 0; y < height; y++) {
  63565. for (var x = 0; x < width; x++) {
  63566. var srcPos = (x + y * width) * 4;
  63567. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  63568. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  63569. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  63570. if (DDSTools.StoreLODInAlphaChannel) {
  63571. destArray[index + 3] = lod;
  63572. }
  63573. else {
  63574. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  63575. }
  63576. index += 4;
  63577. }
  63578. }
  63579. return destArray;
  63580. };
  63581. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63582. if (DDSTools.StoreLODInAlphaChannel) {
  63583. var destArray = new Uint16Array(dataLength);
  63584. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  63585. var index = 0;
  63586. for (var y = 0; y < height; y++) {
  63587. for (var x = 0; x < width; x++) {
  63588. var srcPos = (x + y * width) * 4;
  63589. destArray[index] = srcData[srcPos];
  63590. destArray[index + 1] = srcData[srcPos + 1];
  63591. destArray[index + 2] = srcData[srcPos + 2];
  63592. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  63593. index += 4;
  63594. }
  63595. }
  63596. return destArray;
  63597. }
  63598. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  63599. };
  63600. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63601. if (DDSTools.StoreLODInAlphaChannel) {
  63602. var destArray = new Float32Array(dataLength);
  63603. var srcData = new Float32Array(arrayBuffer, dataOffset);
  63604. var index = 0;
  63605. for (var y = 0; y < height; y++) {
  63606. for (var x = 0; x < width; x++) {
  63607. var srcPos = (x + y * width) * 4;
  63608. destArray[index] = srcData[srcPos];
  63609. destArray[index + 1] = srcData[srcPos + 1];
  63610. destArray[index + 2] = srcData[srcPos + 2];
  63611. destArray[index + 3] = lod;
  63612. index += 4;
  63613. }
  63614. }
  63615. return destArray;
  63616. }
  63617. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  63618. };
  63619. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63620. var destArray = new Uint8Array(dataLength);
  63621. var srcData = new Float32Array(arrayBuffer, dataOffset);
  63622. var index = 0;
  63623. for (var y = 0; y < height; y++) {
  63624. for (var x = 0; x < width; x++) {
  63625. var srcPos = (x + y * width) * 4;
  63626. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  63627. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  63628. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  63629. if (DDSTools.StoreLODInAlphaChannel) {
  63630. destArray[index + 3] = lod;
  63631. }
  63632. else {
  63633. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  63634. }
  63635. index += 4;
  63636. }
  63637. }
  63638. return destArray;
  63639. };
  63640. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63641. var destArray = new Uint8Array(dataLength);
  63642. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  63643. var index = 0;
  63644. for (var y = 0; y < height; y++) {
  63645. for (var x = 0; x < width; x++) {
  63646. var srcPos = (x + y * width) * 4;
  63647. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  63648. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  63649. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  63650. if (DDSTools.StoreLODInAlphaChannel) {
  63651. destArray[index + 3] = lod;
  63652. }
  63653. else {
  63654. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  63655. }
  63656. index += 4;
  63657. }
  63658. }
  63659. return destArray;
  63660. };
  63661. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  63662. var byteArray = new Uint8Array(dataLength);
  63663. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  63664. var index = 0;
  63665. for (var y = 0; y < height; y++) {
  63666. for (var x = 0; x < width; x++) {
  63667. var srcPos = (x + y * width) * 4;
  63668. byteArray[index] = srcData[srcPos + 2];
  63669. byteArray[index + 1] = srcData[srcPos + 1];
  63670. byteArray[index + 2] = srcData[srcPos];
  63671. byteArray[index + 3] = srcData[srcPos + 3];
  63672. index += 4;
  63673. }
  63674. }
  63675. return byteArray;
  63676. };
  63677. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  63678. var byteArray = new Uint8Array(dataLength);
  63679. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  63680. var index = 0;
  63681. for (var y = 0; y < height; y++) {
  63682. for (var x = 0; x < width; x++) {
  63683. var srcPos = (x + y * width) * 3;
  63684. byteArray[index] = srcData[srcPos + 2];
  63685. byteArray[index + 1] = srcData[srcPos + 1];
  63686. byteArray[index + 2] = srcData[srcPos];
  63687. index += 3;
  63688. }
  63689. }
  63690. return byteArray;
  63691. };
  63692. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  63693. var byteArray = new Uint8Array(dataLength);
  63694. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  63695. var index = 0;
  63696. for (var y = 0; y < height; y++) {
  63697. for (var x = 0; x < width; x++) {
  63698. var srcPos = (x + y * width);
  63699. byteArray[index] = srcData[srcPos];
  63700. index++;
  63701. }
  63702. }
  63703. return byteArray;
  63704. };
  63705. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  63706. if (lodIndex === void 0) { lodIndex = -1; }
  63707. var ext = engine.getCaps().s3tc;
  63708. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  63709. if (header[off_magic] != DDS_MAGIC) {
  63710. BABYLON.Tools.Error("Invalid magic number in DDS header");
  63711. return;
  63712. }
  63713. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  63714. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  63715. return;
  63716. }
  63717. if (info.isCompressed && !ext) {
  63718. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  63719. return;
  63720. }
  63721. var bpp = header[off_RGBbpp];
  63722. dataOffset = header[off_size] + 4;
  63723. var computeFormats = false;
  63724. if (info.isFourCC) {
  63725. fourCC = header[off_pfFourCC];
  63726. switch (fourCC) {
  63727. case FOURCC_DXT1:
  63728. blockBytes = 8;
  63729. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  63730. break;
  63731. case FOURCC_DXT3:
  63732. blockBytes = 16;
  63733. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  63734. break;
  63735. case FOURCC_DXT5:
  63736. blockBytes = 16;
  63737. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  63738. break;
  63739. case FOURCC_D3DFMT_R16G16B16A16F:
  63740. computeFormats = true;
  63741. break;
  63742. case FOURCC_D3DFMT_R32G32B32A32F:
  63743. computeFormats = true;
  63744. break;
  63745. case FOURCC_DX10:
  63746. // There is an additionnal header so dataOffset need to be changed
  63747. dataOffset += 5 * 4; // 5 uints
  63748. var supported = false;
  63749. switch (info.dxgiFormat) {
  63750. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  63751. computeFormats = true;
  63752. supported = true;
  63753. break;
  63754. case DXGI_FORMAT_B8G8R8X8_UNORM:
  63755. info.isRGB = true;
  63756. info.isFourCC = false;
  63757. bpp = 32;
  63758. supported = true;
  63759. break;
  63760. }
  63761. if (supported) {
  63762. break;
  63763. }
  63764. default:
  63765. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  63766. return;
  63767. }
  63768. }
  63769. if (computeFormats) {
  63770. format = engine._getWebGLTextureType(info.textureType);
  63771. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  63772. }
  63773. mipmapCount = 1;
  63774. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  63775. mipmapCount = Math.max(1, header[off_mipmapCount]);
  63776. }
  63777. for (var face = 0; face < faces; face++) {
  63778. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  63779. width = header[off_width];
  63780. height = header[off_height];
  63781. for (mip = 0; mip < mipmapCount; ++mip) {
  63782. if (lodIndex === -1 || lodIndex === mip) {
  63783. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  63784. var i = (lodIndex === -1) ? mip : 0;
  63785. if (!info.isCompressed && info.isFourCC) {
  63786. dataLength = width * height * 4;
  63787. var floatArray;
  63788. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  63789. if (bpp === 128) {
  63790. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63791. }
  63792. else if (bpp === 64) {
  63793. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63794. }
  63795. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63796. format = engine._getWebGLTextureType(info.textureType);
  63797. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  63798. }
  63799. else {
  63800. if (bpp === 128) {
  63801. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63802. }
  63803. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  63804. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63805. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63806. format = engine._getWebGLTextureType(info.textureType);
  63807. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  63808. }
  63809. else {
  63810. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63811. }
  63812. }
  63813. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  63814. }
  63815. else if (info.isRGB) {
  63816. if (bpp === 24) {
  63817. dataLength = width * height * 3;
  63818. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  63819. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  63820. }
  63821. else {
  63822. dataLength = width * height * 4;
  63823. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  63824. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  63825. }
  63826. }
  63827. else if (info.isLuminance) {
  63828. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  63829. var unpaddedRowSize = width;
  63830. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  63831. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  63832. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  63833. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  63834. }
  63835. else {
  63836. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  63837. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  63838. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  63839. }
  63840. }
  63841. dataOffset += width * height * (bpp / 8);
  63842. width *= 0.5;
  63843. height *= 0.5;
  63844. width = Math.max(1.0, width);
  63845. height = Math.max(1.0, height);
  63846. }
  63847. }
  63848. };
  63849. return DDSTools;
  63850. }());
  63851. DDSTools.StoreLODInAlphaChannel = false;
  63852. Internals.DDSTools = DDSTools;
  63853. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63854. })(BABYLON || (BABYLON = {}));
  63855. //# sourceMappingURL=babylon.dds.js.map
  63856. var BABYLON;
  63857. (function (BABYLON) {
  63858. var Internals;
  63859. (function (Internals) {
  63860. /**
  63861. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  63862. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  63863. */
  63864. var KhronosTextureContainer = (function () {
  63865. /**
  63866. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  63867. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  63868. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  63869. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  63870. */
  63871. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  63872. this.arrayBuffer = arrayBuffer;
  63873. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  63874. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  63875. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  63876. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  63877. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  63878. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  63879. BABYLON.Tools.Error("texture missing KTX identifier");
  63880. return;
  63881. }
  63882. // load the reset of the header in native 32 bit int
  63883. var header = new Int32Array(this.arrayBuffer, 12, 13);
  63884. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  63885. var oppositeEndianess = header[0] === 0x01020304;
  63886. // read all the header elements in order they exist in the file, without modification (sans endainness)
  63887. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  63888. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  63889. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  63890. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  63891. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  63892. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  63893. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  63894. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  63895. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  63896. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  63897. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  63898. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  63899. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  63900. if (this.glType !== 0) {
  63901. BABYLON.Tools.Error("only compressed formats currently supported");
  63902. return;
  63903. }
  63904. else {
  63905. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  63906. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  63907. }
  63908. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  63909. BABYLON.Tools.Error("only 2D textures currently supported");
  63910. return;
  63911. }
  63912. if (this.numberOfArrayElements !== 0) {
  63913. BABYLON.Tools.Error("texture arrays not currently supported");
  63914. return;
  63915. }
  63916. if (this.numberOfFaces !== facesExpected) {
  63917. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  63918. return;
  63919. }
  63920. // we now have a completely validated file, so could use existence of loadType as success
  63921. // would need to make this more elaborate & adjust checks above to support more than one load type
  63922. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  63923. }
  63924. // not as fast hardware based, but will probably never need to use
  63925. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  63926. return ((val & 0xFF) << 24)
  63927. | ((val & 0xFF00) << 8)
  63928. | ((val >> 8) & 0xFF00)
  63929. | ((val >> 24) & 0xFF);
  63930. };
  63931. /**
  63932. * It is assumed that the texture has already been created & is currently bound
  63933. */
  63934. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  63935. switch (this.loadType) {
  63936. case KhronosTextureContainer.COMPRESSED_2D:
  63937. this._upload2DCompressedLevels(gl, loadMipmaps);
  63938. break;
  63939. case KhronosTextureContainer.TEX_2D:
  63940. case KhronosTextureContainer.COMPRESSED_3D:
  63941. case KhronosTextureContainer.TEX_3D:
  63942. }
  63943. };
  63944. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  63945. // initialize width & height for level 1
  63946. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  63947. var width = this.pixelWidth;
  63948. var height = this.pixelHeight;
  63949. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  63950. for (var level = 0; level < mipmapCount; level++) {
  63951. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  63952. for (var face = 0; face < this.numberOfFaces; face++) {
  63953. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  63954. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  63955. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  63956. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  63957. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  63958. }
  63959. width = Math.max(1.0, width * 0.5);
  63960. height = Math.max(1.0, height * 0.5);
  63961. }
  63962. };
  63963. return KhronosTextureContainer;
  63964. }());
  63965. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  63966. // load types
  63967. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  63968. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  63969. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  63970. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  63971. Internals.KhronosTextureContainer = KhronosTextureContainer;
  63972. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63973. })(BABYLON || (BABYLON = {}));
  63974. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  63975. var BABYLON;
  63976. (function (BABYLON) {
  63977. var DynamicFloatArrayElementInfo = (function () {
  63978. function DynamicFloatArrayElementInfo() {
  63979. }
  63980. return DynamicFloatArrayElementInfo;
  63981. }());
  63982. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  63983. /**
  63984. * 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.
  63985. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  63986. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  63987. * 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.
  63988. * 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.
  63989. * 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".
  63990. */
  63991. var DynamicFloatArray = (function () {
  63992. /**
  63993. * Construct an instance of the dynamic float array
  63994. * @param stride size of one element in float (i.e. not bytes!)
  63995. * @param initialElementCount the number of available entries at construction
  63996. */
  63997. function DynamicFloatArray(stride, initialElementCount) {
  63998. this.compareValueOffset = null;
  63999. this.sortingAscending = true;
  64000. this._stride = stride;
  64001. this.buffer = new Float32Array(stride * initialElementCount);
  64002. this._lastUsed = 0;
  64003. this._firstFree = 0;
  64004. this._allEntries = new Array(initialElementCount);
  64005. this._freeEntries = new Array(initialElementCount);
  64006. for (var i = 0; i < initialElementCount; i++) {
  64007. var element = new DynamicFloatArrayElementInfo();
  64008. element.offset = i * stride;
  64009. this._allEntries[i] = element;
  64010. this._freeEntries[initialElementCount - i - 1] = element;
  64011. }
  64012. }
  64013. /**
  64014. * Allocate an element in the array.
  64015. * @return the element info instance that contains the offset into the main buffer of the element's location.
  64016. * Beware, this offset may change when you call pack()
  64017. */
  64018. DynamicFloatArray.prototype.allocElement = function () {
  64019. if (this._freeEntries.length === 0) {
  64020. this._growBuffer();
  64021. }
  64022. var el = this._freeEntries.pop();
  64023. this._lastUsed = Math.max(el.offset, this._lastUsed);
  64024. if (el.offset === this._firstFree) {
  64025. if (this._freeEntries.length > 0) {
  64026. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  64027. }
  64028. else {
  64029. this._firstFree += this._stride;
  64030. }
  64031. }
  64032. return el;
  64033. };
  64034. /**
  64035. * Free the element corresponding to the given element info
  64036. * @param elInfo the element that describe the allocated element
  64037. */
  64038. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  64039. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  64040. this._freeEntries.push(elInfo);
  64041. };
  64042. /**
  64043. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  64044. * 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().
  64045. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  64046. */
  64047. DynamicFloatArray.prototype.pack = function () {
  64048. // no free slot? no need to pack
  64049. if (this._freeEntries.length === 0) {
  64050. return this.buffer;
  64051. }
  64052. // If the buffer is already packed the last used will always be lower than the first free
  64053. // 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.
  64054. if (this._lastUsed < this._firstFree) {
  64055. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  64056. return elementsBuffer_1;
  64057. }
  64058. var s = this._stride;
  64059. // 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
  64060. var lastFree = new DynamicFloatArrayElementInfo();
  64061. lastFree.offset = this.totalElementCount * s;
  64062. this._freeEntries.push(lastFree);
  64063. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  64064. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  64065. var firstFreeSlotOffset = sortedFree[0].offset;
  64066. var freeZoneSize = 1;
  64067. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  64068. var prevOffset = sortedFree[0].offset;
  64069. for (var i = 1; i < sortedFree.length; i++) {
  64070. // 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
  64071. if (firstFreeSlotOffset >= occupiedZoneSize) {
  64072. break;
  64073. }
  64074. var curFree = sortedFree[i];
  64075. var curOffset = curFree.offset;
  64076. // Compute the distance between this offset and the previous
  64077. var distance = curOffset - prevOffset;
  64078. // If the distance is the stride size, they are adjacent, it good, move to the next
  64079. if (distance === s) {
  64080. // Free zone is one element bigger
  64081. ++freeZoneSize;
  64082. // as we're about to iterate to the next, the cur becomes the previous...
  64083. prevOffset = curOffset;
  64084. continue;
  64085. }
  64086. // Distance is bigger, which means there's x element between the previous free and this one
  64087. var usedRange = (distance / s) - 1;
  64088. // Two cases the free zone is smaller than the data to move or bigger
  64089. // Copy what can fit in the free zone
  64090. var curMoveOffset = curOffset - s;
  64091. var copyCount = Math.min(freeZoneSize, usedRange);
  64092. for (var j = 0; j < copyCount; j++) {
  64093. var freeI = firstFreeSlotOffset / s;
  64094. var curI = curMoveOffset / s;
  64095. var moveEl = sortedAll[curI];
  64096. this._moveElement(moveEl, firstFreeSlotOffset);
  64097. var replacedEl = sortedAll[freeI];
  64098. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  64099. replacedEl.offset = curMoveOffset;
  64100. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  64101. sortedAll[freeI] = moveEl;
  64102. sortedAll[curI] = replacedEl;
  64103. curMoveOffset -= s;
  64104. firstFreeSlotOffset += s;
  64105. }
  64106. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  64107. if (freeZoneSize <= usedRange) {
  64108. firstFreeSlotOffset = curMoveOffset + s;
  64109. freeZoneSize = 1 + copyCount;
  64110. }
  64111. else {
  64112. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  64113. }
  64114. // as we're about to iterate to the next, the cur becomes the previous...
  64115. prevOffset = curOffset;
  64116. }
  64117. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  64118. this._lastUsed = firstFreeSlotOffset - s;
  64119. this._firstFree = firstFreeSlotOffset;
  64120. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  64121. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  64122. this._allEntries = sortedAll;
  64123. return elementsBuffer;
  64124. };
  64125. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  64126. for (var i = 0; i < this._stride; i++) {
  64127. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  64128. }
  64129. element.offset = destOffset;
  64130. };
  64131. DynamicFloatArray.prototype._growBuffer = function () {
  64132. // Allocate the new buffer with 50% more entries, copy the content of the current one
  64133. var newElCount = Math.floor(this.totalElementCount * 1.5);
  64134. var newBuffer = new Float32Array(newElCount * this._stride);
  64135. newBuffer.set(this.buffer);
  64136. var curCount = this.totalElementCount;
  64137. var addedCount = newElCount - this.totalElementCount;
  64138. for (var i = 0; i < addedCount; i++) {
  64139. var element = new DynamicFloatArrayElementInfo();
  64140. element.offset = (curCount + i) * this.stride;
  64141. this._allEntries.push(element);
  64142. this._freeEntries[addedCount - i - 1] = element;
  64143. }
  64144. this._firstFree = curCount * this.stride;
  64145. this.buffer = newBuffer;
  64146. };
  64147. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  64148. /**
  64149. * Get the total count of entries that can fit in the current buffer
  64150. * @returns the elements count
  64151. */
  64152. get: function () {
  64153. return this._allEntries.length;
  64154. },
  64155. enumerable: true,
  64156. configurable: true
  64157. });
  64158. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  64159. /**
  64160. * Get the count of free entries that can still be allocated without resizing the buffer
  64161. * @returns the free elements count
  64162. */
  64163. get: function () {
  64164. return this._freeEntries.length;
  64165. },
  64166. enumerable: true,
  64167. configurable: true
  64168. });
  64169. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  64170. /**
  64171. * Get the count of allocated elements
  64172. * @returns the allocated elements count
  64173. */
  64174. get: function () {
  64175. return this._allEntries.length - this._freeEntries.length;
  64176. },
  64177. enumerable: true,
  64178. configurable: true
  64179. });
  64180. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  64181. /**
  64182. * Return the size of one element in float
  64183. * @returns the size in float
  64184. */
  64185. get: function () {
  64186. return this._stride;
  64187. },
  64188. enumerable: true,
  64189. configurable: true
  64190. });
  64191. DynamicFloatArray.prototype.sort = function () {
  64192. var _this = this;
  64193. if (!this.compareValueOffset) {
  64194. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  64195. }
  64196. var count = this.usedElementCount;
  64197. // Do we have to (re)create the sort table?
  64198. if (!this._sortTable || this._sortTable.length < count) {
  64199. // 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...
  64200. var newCount = Math.min(this.totalElementCount, count * 2);
  64201. this._sortTable = new Array(newCount);
  64202. }
  64203. if (!this._sortedTable || this._sortedTable.length !== count) {
  64204. this._sortedTable = new Array(count);
  64205. }
  64206. // Because, you know...
  64207. this.pack();
  64208. //let stride = this.stride;
  64209. //for (let i = 0; i < count; i++) {
  64210. // let si = this._sortTable[i];
  64211. // if (!si) {
  64212. // si = new SortInfo();
  64213. // this._sortTable[i] = si;
  64214. // }
  64215. // si.entry = this._allEntries[i];
  64216. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  64217. // si.swapedOffset = null;
  64218. // this._sortedTable[i] = si;
  64219. //}
  64220. var curOffset = 0;
  64221. var stride = this.stride;
  64222. for (var i = 0; i < count; i++, curOffset += stride) {
  64223. var si = this._sortTable[i];
  64224. if (!si) {
  64225. si = new SortInfo();
  64226. this._sortTable[i] = si;
  64227. }
  64228. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  64229. si.offset = curOffset;
  64230. si.swapedOffset = null;
  64231. this._sortedTable[i] = si;
  64232. }
  64233. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  64234. if (this.sortingAscending) {
  64235. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  64236. }
  64237. else {
  64238. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  64239. }
  64240. var swapElements = function (src, dst) {
  64241. for (var i = 0; i < stride; i++) {
  64242. var tps = _this.buffer[dst + i];
  64243. _this.buffer[dst + i] = _this.buffer[src + i];
  64244. _this.buffer[src + i] = tps;
  64245. }
  64246. };
  64247. // 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:
  64248. // 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),
  64249. // and I still want something with a good algorithm complexity.
  64250. // 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,
  64251. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  64252. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  64253. // 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
  64254. // until we find a SortInfo object without a swapedOffset which means we got the right location
  64255. // 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
  64256. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  64257. for (var i = 0; i < count; i++) {
  64258. // Get the element to move
  64259. var sourceSI = this._sortedTable[i];
  64260. var destSI = this._sortTable[i];
  64261. var sourceOff = sourceSI.offset;
  64262. // If the source changed location, find the new one
  64263. if (sourceSI.swapedOffset) {
  64264. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  64265. var curSI = sourceSI;
  64266. while (curSI.swapedOffset) {
  64267. curSI = this._sortTable[curSI.swapedOffset / stride];
  64268. }
  64269. // Finally get the right location
  64270. sourceOff = curSI.offset;
  64271. }
  64272. // Tag the element being replaced with its new location
  64273. destSI.swapedOffset = sourceOff;
  64274. // Swap elements (only if needed)
  64275. if (sourceOff !== destSI.offset) {
  64276. swapElements(sourceOff, destSI.offset);
  64277. }
  64278. // Update the offset in the corresponding DFAE
  64279. //sourceSI.entry.offset = destSI.entry.offset;
  64280. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  64281. }
  64282. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  64283. return true;
  64284. };
  64285. return DynamicFloatArray;
  64286. }());
  64287. BABYLON.DynamicFloatArray = DynamicFloatArray;
  64288. var SortInfo = (function () {
  64289. function SortInfo() {
  64290. this.compareData = this.offset = this.swapedOffset = null;
  64291. }
  64292. return SortInfo;
  64293. }());
  64294. })(BABYLON || (BABYLON = {}));
  64295. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  64296. var BABYLON;
  64297. (function (BABYLON) {
  64298. var Debug;
  64299. (function (Debug) {
  64300. /**
  64301. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  64302. */
  64303. var SkeletonViewer = (function () {
  64304. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  64305. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  64306. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  64307. this.skeleton = skeleton;
  64308. this.mesh = mesh;
  64309. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  64310. this.renderingGroupId = renderingGroupId;
  64311. this.color = BABYLON.Color3.White();
  64312. this._debugLines = [];
  64313. this._isEnabled = false;
  64314. this._scene = scene;
  64315. this.update();
  64316. this._renderFunction = this.update.bind(this);
  64317. }
  64318. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  64319. get: function () {
  64320. return this._isEnabled;
  64321. },
  64322. set: function (value) {
  64323. if (this._isEnabled === value) {
  64324. return;
  64325. }
  64326. this._isEnabled = value;
  64327. if (value) {
  64328. this._scene.registerBeforeRender(this._renderFunction);
  64329. }
  64330. else {
  64331. this._scene.unregisterBeforeRender(this._renderFunction);
  64332. }
  64333. },
  64334. enumerable: true,
  64335. configurable: true
  64336. });
  64337. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  64338. if (x === void 0) { x = 0; }
  64339. if (y === void 0) { y = 0; }
  64340. if (z === void 0) { z = 0; }
  64341. var tmat = BABYLON.Tmp.Matrix[0];
  64342. var parentBone = bone.getParent();
  64343. tmat.copyFrom(bone.getLocalMatrix());
  64344. if (x !== 0 || y !== 0 || z !== 0) {
  64345. var tmat2 = BABYLON.Tmp.Matrix[1];
  64346. BABYLON.Matrix.IdentityToRef(tmat2);
  64347. tmat2.m[12] = x;
  64348. tmat2.m[13] = y;
  64349. tmat2.m[14] = z;
  64350. tmat2.multiplyToRef(tmat, tmat);
  64351. }
  64352. if (parentBone) {
  64353. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  64354. }
  64355. tmat.multiplyToRef(meshMat, tmat);
  64356. position.x = tmat.m[12];
  64357. position.y = tmat.m[13];
  64358. position.z = tmat.m[14];
  64359. };
  64360. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  64361. var len = bones.length;
  64362. var meshPos = this.mesh.position;
  64363. for (var i = 0; i < len; i++) {
  64364. var bone = bones[i];
  64365. var points = this._debugLines[i];
  64366. if (!points) {
  64367. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64368. this._debugLines[i] = points;
  64369. }
  64370. this._getBonePosition(points[0], bone, meshMat);
  64371. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  64372. points[0].subtractInPlace(meshPos);
  64373. points[1].subtractInPlace(meshPos);
  64374. }
  64375. };
  64376. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  64377. var len = bones.length;
  64378. var boneNum = 0;
  64379. var meshPos = this.mesh.position;
  64380. for (var i = len - 1; i >= 0; i--) {
  64381. var childBone = bones[i];
  64382. var parentBone = childBone.getParent();
  64383. if (!parentBone) {
  64384. continue;
  64385. }
  64386. var points = this._debugLines[boneNum];
  64387. if (!points) {
  64388. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64389. this._debugLines[boneNum] = points;
  64390. }
  64391. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  64392. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  64393. points[0].subtractInPlace(meshPos);
  64394. points[1].subtractInPlace(meshPos);
  64395. boneNum++;
  64396. }
  64397. };
  64398. SkeletonViewer.prototype.update = function () {
  64399. if (this.autoUpdateBonesMatrices) {
  64400. this.skeleton.computeAbsoluteTransforms();
  64401. }
  64402. if (this.skeleton.bones[0].length === undefined) {
  64403. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64404. }
  64405. else {
  64406. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64407. }
  64408. if (!this._debugMesh) {
  64409. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  64410. this._debugMesh.renderingGroupId = this.renderingGroupId;
  64411. }
  64412. else {
  64413. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  64414. }
  64415. this._debugMesh.position.copyFrom(this.mesh.position);
  64416. this._debugMesh.color = this.color;
  64417. };
  64418. SkeletonViewer.prototype.dispose = function () {
  64419. if (this._debugMesh) {
  64420. this.isEnabled = false;
  64421. this._debugMesh.dispose();
  64422. this._debugMesh = null;
  64423. }
  64424. };
  64425. return SkeletonViewer;
  64426. }());
  64427. Debug.SkeletonViewer = SkeletonViewer;
  64428. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64429. })(BABYLON || (BABYLON = {}));
  64430. //# sourceMappingURL=babylon.skeletonViewer.js.map
  64431. var BABYLON;
  64432. (function (BABYLON) {
  64433. var Debug;
  64434. (function (Debug) {
  64435. var AxesViewer = (function () {
  64436. function AxesViewer(scene, scaleLines) {
  64437. if (scaleLines === void 0) { scaleLines = 1; }
  64438. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64439. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64440. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64441. this.scaleLines = 1;
  64442. this.scaleLines = scaleLines;
  64443. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  64444. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  64445. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  64446. this._xmesh.renderingGroupId = 2;
  64447. this._ymesh.renderingGroupId = 2;
  64448. this._zmesh.renderingGroupId = 2;
  64449. this._xmesh.material.checkReadyOnlyOnce = true;
  64450. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  64451. this._ymesh.material.checkReadyOnlyOnce = true;
  64452. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  64453. this._zmesh.material.checkReadyOnlyOnce = true;
  64454. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  64455. this.scene = scene;
  64456. }
  64457. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  64458. var scaleLines = this.scaleLines;
  64459. this._xmesh.position.copyFrom(position);
  64460. this._ymesh.position.copyFrom(position);
  64461. this._zmesh.position.copyFrom(position);
  64462. var point2 = this._xline[1];
  64463. point2.x = xaxis.x * scaleLines;
  64464. point2.y = xaxis.y * scaleLines;
  64465. point2.z = xaxis.z * scaleLines;
  64466. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  64467. point2 = this._yline[1];
  64468. point2.x = yaxis.x * scaleLines;
  64469. point2.y = yaxis.y * scaleLines;
  64470. point2.z = yaxis.z * scaleLines;
  64471. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  64472. point2 = this._zline[1];
  64473. point2.x = zaxis.x * scaleLines;
  64474. point2.y = zaxis.y * scaleLines;
  64475. point2.z = zaxis.z * scaleLines;
  64476. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  64477. };
  64478. AxesViewer.prototype.dispose = function () {
  64479. if (this._xmesh) {
  64480. this._xmesh.dispose();
  64481. this._ymesh.dispose();
  64482. this._zmesh.dispose();
  64483. this._xmesh = null;
  64484. this._ymesh = null;
  64485. this._zmesh = null;
  64486. this._xline = null;
  64487. this._yline = null;
  64488. this._zline = null;
  64489. this.scene = null;
  64490. }
  64491. };
  64492. return AxesViewer;
  64493. }());
  64494. Debug.AxesViewer = AxesViewer;
  64495. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64496. })(BABYLON || (BABYLON = {}));
  64497. //# sourceMappingURL=babylon.axesViewer.js.map
  64498. var BABYLON;
  64499. (function (BABYLON) {
  64500. var Debug;
  64501. (function (Debug) {
  64502. var BoneAxesViewer = (function (_super) {
  64503. __extends(BoneAxesViewer, _super);
  64504. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  64505. if (scaleLines === void 0) { scaleLines = 1; }
  64506. var _this = _super.call(this, scene, scaleLines) || this;
  64507. _this.pos = BABYLON.Vector3.Zero();
  64508. _this.xaxis = BABYLON.Vector3.Zero();
  64509. _this.yaxis = BABYLON.Vector3.Zero();
  64510. _this.zaxis = BABYLON.Vector3.Zero();
  64511. _this.mesh = mesh;
  64512. _this.bone = bone;
  64513. return _this;
  64514. }
  64515. BoneAxesViewer.prototype.update = function () {
  64516. var bone = this.bone;
  64517. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  64518. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  64519. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  64520. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  64521. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  64522. };
  64523. BoneAxesViewer.prototype.dispose = function () {
  64524. if (this.pos) {
  64525. this.pos = null;
  64526. this.xaxis = null;
  64527. this.yaxis = null;
  64528. this.zaxis = null;
  64529. this.mesh = null;
  64530. this.bone = null;
  64531. _super.prototype.dispose.call(this);
  64532. }
  64533. };
  64534. return BoneAxesViewer;
  64535. }(Debug.AxesViewer));
  64536. Debug.BoneAxesViewer = BoneAxesViewer;
  64537. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64538. })(BABYLON || (BABYLON = {}));
  64539. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  64540. var BABYLON;
  64541. (function (BABYLON) {
  64542. var RayHelper = (function () {
  64543. function RayHelper(ray) {
  64544. this.ray = ray;
  64545. }
  64546. RayHelper.CreateAndShow = function (ray, scene, color) {
  64547. var helper = new RayHelper(ray);
  64548. helper.show(scene, color);
  64549. return helper;
  64550. };
  64551. RayHelper.prototype.show = function (scene, color) {
  64552. if (!this._renderFunction) {
  64553. var ray = this.ray;
  64554. this._renderFunction = this._render.bind(this);
  64555. this._scene = scene;
  64556. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  64557. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  64558. this._scene.registerBeforeRender(this._renderFunction);
  64559. }
  64560. if (color) {
  64561. this._renderLine.color.copyFrom(color);
  64562. }
  64563. };
  64564. RayHelper.prototype.hide = function () {
  64565. if (this._renderFunction) {
  64566. this._scene.unregisterBeforeRender(this._renderFunction);
  64567. this._scene = null;
  64568. this._renderFunction = null;
  64569. this._renderLine.dispose();
  64570. this._renderLine = null;
  64571. this._renderPoints = null;
  64572. }
  64573. };
  64574. RayHelper.prototype._render = function () {
  64575. var ray = this.ray;
  64576. var point = this._renderPoints[1];
  64577. var len = Math.min(ray.length, 1000000);
  64578. point.copyFrom(ray.direction);
  64579. point.scaleInPlace(len);
  64580. point.addInPlace(ray.origin);
  64581. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  64582. };
  64583. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  64584. this._attachedToMesh = mesh;
  64585. var ray = this.ray;
  64586. if (!ray.direction) {
  64587. ray.direction = BABYLON.Vector3.Zero();
  64588. }
  64589. if (!ray.origin) {
  64590. ray.origin = BABYLON.Vector3.Zero();
  64591. }
  64592. if (length) {
  64593. ray.length = length;
  64594. }
  64595. if (!meshSpaceOrigin) {
  64596. meshSpaceOrigin = BABYLON.Vector3.Zero();
  64597. }
  64598. if (!meshSpaceDirection) {
  64599. // -1 so that this will work with Mesh.lookAt
  64600. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  64601. }
  64602. if (!this._meshSpaceDirection) {
  64603. this._meshSpaceDirection = meshSpaceDirection.clone();
  64604. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  64605. }
  64606. else {
  64607. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  64608. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  64609. }
  64610. if (!this._updateToMeshFunction) {
  64611. this._updateToMeshFunction = this._updateToMesh.bind(this);
  64612. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  64613. }
  64614. this._updateToMesh();
  64615. };
  64616. RayHelper.prototype.detachFromMesh = function () {
  64617. if (this._attachedToMesh) {
  64618. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  64619. this._attachedToMesh = null;
  64620. this._updateToMeshFunction = null;
  64621. }
  64622. };
  64623. RayHelper.prototype._updateToMesh = function () {
  64624. var ray = this.ray;
  64625. if (this._attachedToMesh._isDisposed) {
  64626. this.detachFromMesh();
  64627. return;
  64628. }
  64629. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  64630. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  64631. };
  64632. RayHelper.prototype.dispose = function () {
  64633. this.hide();
  64634. this.detachFromMesh();
  64635. this.ray = null;
  64636. };
  64637. return RayHelper;
  64638. }());
  64639. BABYLON.RayHelper = RayHelper;
  64640. })(BABYLON || (BABYLON = {}));
  64641. //# sourceMappingURL=babylon.rayHelper.js.map
  64642. var BABYLON;
  64643. (function (BABYLON) {
  64644. var DebugLayer = (function () {
  64645. function DebugLayer(scene) {
  64646. this._scene = scene;
  64647. }
  64648. /** Creates the inspector window. */
  64649. DebugLayer.prototype._createInspector = function (config) {
  64650. if (config === void 0) { config = {}; }
  64651. var popup = config.popup || false;
  64652. var initialTab = config.initialTab || 0;
  64653. var parentElement = config.parentElement || null;
  64654. if (!this._inspector) {
  64655. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  64656. } // else nothing to do,; instance is already existing
  64657. };
  64658. DebugLayer.prototype.isVisible = function () {
  64659. if (!this._inspector) {
  64660. return false;
  64661. }
  64662. return true;
  64663. };
  64664. DebugLayer.prototype.hide = function () {
  64665. if (this._inspector) {
  64666. try {
  64667. this._inspector.dispose();
  64668. }
  64669. catch (e) {
  64670. // If the inspector has been removed directly from the inspector tool
  64671. }
  64672. this._inspector = null;
  64673. }
  64674. };
  64675. DebugLayer.prototype.show = function (config) {
  64676. if (config === void 0) { config = {}; }
  64677. if (typeof INSPECTOR == 'undefined') {
  64678. // Load inspector and add it to the DOM
  64679. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  64680. }
  64681. else {
  64682. // Otherwise creates the inspector
  64683. this._createInspector(config);
  64684. }
  64685. };
  64686. return DebugLayer;
  64687. }());
  64688. // Get protocol used - http or https
  64689. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  64690. BABYLON.DebugLayer = DebugLayer;
  64691. })(BABYLON || (BABYLON = {}));
  64692. //# sourceMappingURL=babylon.debugLayer.js.map
  64693. var BABYLON;
  64694. (function (BABYLON) {
  64695. var Debug;
  64696. (function (Debug) {
  64697. var PhysicsViewer = (function () {
  64698. function PhysicsViewer(scene) {
  64699. this._impostors = [];
  64700. this._meshes = [];
  64701. this._numMeshes = 0;
  64702. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64703. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  64704. }
  64705. PhysicsViewer.prototype._updateDebugMeshes = function () {
  64706. var plugin = this._physicsEnginePlugin;
  64707. for (var i = 0; i < this._numMeshes; i++) {
  64708. if (this._impostors[i].isDisposed) {
  64709. this.hideImpostor(this._impostors[i--]);
  64710. }
  64711. else {
  64712. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  64713. }
  64714. }
  64715. };
  64716. PhysicsViewer.prototype.showImpostor = function (impostor) {
  64717. for (var i = 0; i < this._numMeshes; i++) {
  64718. if (this._impostors[i] == impostor) {
  64719. return;
  64720. }
  64721. }
  64722. var debugMesh = this._getDebugMesh(impostor, this._scene);
  64723. if (debugMesh) {
  64724. this._impostors[this._numMeshes] = impostor;
  64725. this._meshes[this._numMeshes] = debugMesh;
  64726. if (this._numMeshes === 0) {
  64727. this._renderFunction = this._updateDebugMeshes.bind(this);
  64728. this._scene.registerBeforeRender(this._renderFunction);
  64729. }
  64730. this._numMeshes++;
  64731. }
  64732. };
  64733. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  64734. var removed = false;
  64735. for (var i = 0; i < this._numMeshes; i++) {
  64736. if (this._impostors[i] == impostor) {
  64737. this._scene.removeMesh(this._meshes[i]);
  64738. this._meshes[i].dispose();
  64739. this._numMeshes--;
  64740. if (this._numMeshes > 0) {
  64741. this._meshes[i] = this._meshes[this._numMeshes];
  64742. this._impostors[i] = this._impostors[this._numMeshes];
  64743. this._meshes[this._numMeshes] = null;
  64744. this._impostors[this._numMeshes] = null;
  64745. }
  64746. else {
  64747. this._meshes[0] = null;
  64748. this._impostors[0] = null;
  64749. }
  64750. removed = true;
  64751. break;
  64752. }
  64753. }
  64754. if (removed && this._numMeshes === 0) {
  64755. this._scene.unregisterBeforeRender(this._renderFunction);
  64756. }
  64757. };
  64758. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  64759. if (!this._debugMaterial) {
  64760. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  64761. this._debugMaterial.wireframe = true;
  64762. }
  64763. return this._debugMaterial;
  64764. };
  64765. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  64766. if (!this._debugBoxMesh) {
  64767. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  64768. this._debugBoxMesh.renderingGroupId = 1;
  64769. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64770. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  64771. scene.removeMesh(this._debugBoxMesh);
  64772. }
  64773. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  64774. };
  64775. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  64776. if (!this._debugSphereMesh) {
  64777. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  64778. this._debugSphereMesh.renderingGroupId = 1;
  64779. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64780. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  64781. scene.removeMesh(this._debugSphereMesh);
  64782. }
  64783. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  64784. };
  64785. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  64786. var body = impostor.physicsBody;
  64787. var shape = body.shapes[0];
  64788. var mesh;
  64789. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  64790. mesh = this._getDebugBoxMesh(scene);
  64791. impostor.getBoxSizeToRef(mesh.scaling);
  64792. }
  64793. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  64794. mesh = this._getDebugSphereMesh(scene);
  64795. var radius = impostor.getRadius();
  64796. mesh.scaling.x = radius * 2;
  64797. mesh.scaling.y = radius * 2;
  64798. mesh.scaling.z = radius * 2;
  64799. }
  64800. return mesh;
  64801. };
  64802. PhysicsViewer.prototype.dispose = function () {
  64803. for (var i = 0; i < this._numMeshes; i++) {
  64804. this.hideImpostor(this._impostors[i]);
  64805. }
  64806. if (this._debugBoxMesh) {
  64807. this._debugBoxMesh.dispose();
  64808. }
  64809. if (this._debugSphereMesh) {
  64810. this._debugSphereMesh.dispose();
  64811. }
  64812. if (this._debugMaterial) {
  64813. this._debugMaterial.dispose();
  64814. }
  64815. this._impostors.length = 0;
  64816. this._scene = null;
  64817. this._physicsEnginePlugin = null;
  64818. };
  64819. return PhysicsViewer;
  64820. }());
  64821. Debug.PhysicsViewer = PhysicsViewer;
  64822. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64823. })(BABYLON || (BABYLON = {}));
  64824. //# sourceMappingURL=babylon.physicsViewer.js.map
  64825. var BABYLON;
  64826. (function (BABYLON) {
  64827. var BoundingBoxRenderer = (function () {
  64828. function BoundingBoxRenderer(scene) {
  64829. this.frontColor = new BABYLON.Color3(1, 1, 1);
  64830. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  64831. this.showBackLines = true;
  64832. this.renderList = new BABYLON.SmartArray(32);
  64833. this._vertexBuffers = {};
  64834. this._scene = scene;
  64835. }
  64836. BoundingBoxRenderer.prototype._prepareRessources = function () {
  64837. if (this._colorShader) {
  64838. return;
  64839. }
  64840. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  64841. attributes: [BABYLON.VertexBuffer.PositionKind],
  64842. uniforms: ["world", "viewProjection", "color"]
  64843. });
  64844. var engine = this._scene.getEngine();
  64845. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  64846. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  64847. this._createIndexBuffer();
  64848. };
  64849. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  64850. var engine = this._scene.getEngine();
  64851. 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]);
  64852. };
  64853. BoundingBoxRenderer.prototype._rebuild = function () {
  64854. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  64855. this._createIndexBuffer();
  64856. };
  64857. BoundingBoxRenderer.prototype.reset = function () {
  64858. this.renderList.reset();
  64859. };
  64860. BoundingBoxRenderer.prototype.render = function () {
  64861. if (this.renderList.length === 0) {
  64862. return;
  64863. }
  64864. this._prepareRessources();
  64865. if (!this._colorShader.isReady()) {
  64866. return;
  64867. }
  64868. var engine = this._scene.getEngine();
  64869. engine.setDepthWrite(false);
  64870. this._colorShader._preBind();
  64871. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  64872. var boundingBox = this.renderList.data[boundingBoxIndex];
  64873. var min = boundingBox.minimum;
  64874. var max = boundingBox.maximum;
  64875. var diff = max.subtract(min);
  64876. var median = min.add(diff.scale(0.5));
  64877. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64878. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64879. .multiply(boundingBox.getWorldMatrix());
  64880. // VBOs
  64881. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64882. if (this.showBackLines) {
  64883. // Back
  64884. engine.setDepthFunctionToGreaterOrEqual();
  64885. this._scene.resetCachedMaterial();
  64886. this._colorShader.setColor4("color", this.backColor.toColor4());
  64887. this._colorShader.bind(worldMatrix);
  64888. // Draw order
  64889. engine.draw(false, 0, 24);
  64890. }
  64891. // Front
  64892. engine.setDepthFunctionToLess();
  64893. this._scene.resetCachedMaterial();
  64894. this._colorShader.setColor4("color", this.frontColor.toColor4());
  64895. this._colorShader.bind(worldMatrix);
  64896. // Draw order
  64897. engine.draw(false, 0, 24);
  64898. }
  64899. this._colorShader.unbind();
  64900. engine.setDepthFunctionToLessOrEqual();
  64901. engine.setDepthWrite(true);
  64902. };
  64903. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  64904. this._prepareRessources();
  64905. if (!this._colorShader.isReady()) {
  64906. return;
  64907. }
  64908. var engine = this._scene.getEngine();
  64909. engine.setDepthWrite(false);
  64910. engine.setColorWrite(false);
  64911. this._colorShader._preBind();
  64912. var boundingBox = mesh._boundingInfo.boundingBox;
  64913. var min = boundingBox.minimum;
  64914. var max = boundingBox.maximum;
  64915. var diff = max.subtract(min);
  64916. var median = min.add(diff.scale(0.5));
  64917. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64918. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64919. .multiply(boundingBox.getWorldMatrix());
  64920. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64921. engine.setDepthFunctionToLess();
  64922. this._scene.resetCachedMaterial();
  64923. this._colorShader.bind(worldMatrix);
  64924. engine.draw(false, 0, 24);
  64925. this._colorShader.unbind();
  64926. engine.setDepthFunctionToLessOrEqual();
  64927. engine.setDepthWrite(true);
  64928. engine.setColorWrite(true);
  64929. };
  64930. BoundingBoxRenderer.prototype.dispose = function () {
  64931. if (!this._colorShader) {
  64932. return;
  64933. }
  64934. this.renderList.dispose();
  64935. this._colorShader.dispose();
  64936. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64937. if (buffer) {
  64938. buffer.dispose();
  64939. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64940. }
  64941. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64942. };
  64943. return BoundingBoxRenderer;
  64944. }());
  64945. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  64946. })(BABYLON || (BABYLON = {}));
  64947. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  64948. var BABYLON;
  64949. (function (BABYLON) {
  64950. var MorphTarget = (function () {
  64951. function MorphTarget(name, influence) {
  64952. if (influence === void 0) { influence = 0; }
  64953. this.name = name;
  64954. this.animations = new Array();
  64955. this.onInfluenceChanged = new BABYLON.Observable();
  64956. this.influence = influence;
  64957. }
  64958. Object.defineProperty(MorphTarget.prototype, "influence", {
  64959. get: function () {
  64960. return this._influence;
  64961. },
  64962. set: function (influence) {
  64963. if (this._influence === influence) {
  64964. return;
  64965. }
  64966. var previous = this._influence;
  64967. this._influence = influence;
  64968. if (this.onInfluenceChanged.hasObservers) {
  64969. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  64970. }
  64971. },
  64972. enumerable: true,
  64973. configurable: true
  64974. });
  64975. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  64976. get: function () {
  64977. return this._normals !== undefined;
  64978. },
  64979. enumerable: true,
  64980. configurable: true
  64981. });
  64982. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  64983. get: function () {
  64984. return this._tangents !== undefined;
  64985. },
  64986. enumerable: true,
  64987. configurable: true
  64988. });
  64989. MorphTarget.prototype.setPositions = function (data) {
  64990. this._positions = new Float32Array(data);
  64991. };
  64992. MorphTarget.prototype.getPositions = function () {
  64993. return this._positions;
  64994. };
  64995. MorphTarget.prototype.setNormals = function (data) {
  64996. this._normals = new Float32Array(data);
  64997. };
  64998. MorphTarget.prototype.getNormals = function () {
  64999. return this._normals;
  65000. };
  65001. MorphTarget.prototype.setTangents = function (data) {
  65002. this._tangents = new Float32Array(data);
  65003. };
  65004. MorphTarget.prototype.getTangents = function () {
  65005. return this._tangents;
  65006. };
  65007. /**
  65008. * Serializes the current target into a Serialization object.
  65009. * Returns the serialized object.
  65010. */
  65011. MorphTarget.prototype.serialize = function () {
  65012. var serializationObject = {};
  65013. serializationObject.name = this.name;
  65014. serializationObject.influence = this.influence;
  65015. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  65016. if (this.hasNormals) {
  65017. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  65018. }
  65019. if (this.hasTangents) {
  65020. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  65021. }
  65022. return serializationObject;
  65023. };
  65024. // Statics
  65025. MorphTarget.Parse = function (serializationObject) {
  65026. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  65027. result.setPositions(serializationObject.positions);
  65028. if (serializationObject.normals) {
  65029. result.setNormals(serializationObject.normals);
  65030. }
  65031. if (serializationObject.tangents) {
  65032. result.setTangents(serializationObject.tangents);
  65033. }
  65034. return result;
  65035. };
  65036. MorphTarget.FromMesh = function (mesh, name, influence) {
  65037. if (!name) {
  65038. name = mesh.name;
  65039. }
  65040. var result = new MorphTarget(name, influence);
  65041. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  65042. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  65043. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  65044. }
  65045. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  65046. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  65047. }
  65048. return result;
  65049. };
  65050. return MorphTarget;
  65051. }());
  65052. BABYLON.MorphTarget = MorphTarget;
  65053. })(BABYLON || (BABYLON = {}));
  65054. //# sourceMappingURL=babylon.morphTarget.js.map
  65055. var BABYLON;
  65056. (function (BABYLON) {
  65057. var MorphTargetManager = (function () {
  65058. function MorphTargetManager(scene) {
  65059. this._targets = new Array();
  65060. this._targetObservable = new Array();
  65061. this._activeTargets = new BABYLON.SmartArray(16);
  65062. this._supportsNormals = false;
  65063. this._supportsTangents = false;
  65064. this._vertexCount = 0;
  65065. this._uniqueId = 0;
  65066. this._tempInfluences = new Array();
  65067. if (!scene) {
  65068. scene = BABYLON.Engine.LastCreatedScene;
  65069. }
  65070. this._scene = scene;
  65071. this._scene.morphTargetManagers.push(this);
  65072. this._uniqueId = scene.getUniqueId();
  65073. }
  65074. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  65075. get: function () {
  65076. return this._uniqueId;
  65077. },
  65078. enumerable: true,
  65079. configurable: true
  65080. });
  65081. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  65082. get: function () {
  65083. return this._vertexCount;
  65084. },
  65085. enumerable: true,
  65086. configurable: true
  65087. });
  65088. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  65089. get: function () {
  65090. return this._supportsNormals;
  65091. },
  65092. enumerable: true,
  65093. configurable: true
  65094. });
  65095. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  65096. get: function () {
  65097. return this._supportsTangents;
  65098. },
  65099. enumerable: true,
  65100. configurable: true
  65101. });
  65102. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  65103. get: function () {
  65104. return this._targets.length;
  65105. },
  65106. enumerable: true,
  65107. configurable: true
  65108. });
  65109. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  65110. get: function () {
  65111. return this._activeTargets.length;
  65112. },
  65113. enumerable: true,
  65114. configurable: true
  65115. });
  65116. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  65117. get: function () {
  65118. return this._influences;
  65119. },
  65120. enumerable: true,
  65121. configurable: true
  65122. });
  65123. MorphTargetManager.prototype.getActiveTarget = function (index) {
  65124. return this._activeTargets.data[index];
  65125. };
  65126. MorphTargetManager.prototype.getTarget = function (index) {
  65127. return this._targets[index];
  65128. };
  65129. MorphTargetManager.prototype.addTarget = function (target) {
  65130. var _this = this;
  65131. if (this._vertexCount) {
  65132. if (this._vertexCount !== target.getPositions().length / 3) {
  65133. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  65134. return;
  65135. }
  65136. }
  65137. this._targets.push(target);
  65138. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  65139. _this._syncActiveTargets(needUpdate);
  65140. }));
  65141. this._syncActiveTargets(true);
  65142. };
  65143. MorphTargetManager.prototype.removeTarget = function (target) {
  65144. var index = this._targets.indexOf(target);
  65145. if (index >= 0) {
  65146. this._targets.splice(index, 1);
  65147. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  65148. this._vertexCount = 0;
  65149. this._syncActiveTargets(true);
  65150. }
  65151. };
  65152. /**
  65153. * Serializes the current manager into a Serialization object.
  65154. * Returns the serialized object.
  65155. */
  65156. MorphTargetManager.prototype.serialize = function () {
  65157. var serializationObject = {};
  65158. serializationObject.id = this.uniqueId;
  65159. serializationObject.targets = [];
  65160. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  65161. var target = _a[_i];
  65162. serializationObject.targets.push(target.serialize());
  65163. }
  65164. return serializationObject;
  65165. };
  65166. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  65167. this._syncActiveTargets(needUpdate);
  65168. };
  65169. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  65170. var influenceCount = 0;
  65171. this._activeTargets.reset();
  65172. this._supportsNormals = true;
  65173. this._supportsTangents = true;
  65174. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  65175. var target = _a[_i];
  65176. if (target.influence > 0) {
  65177. this._activeTargets.push(target);
  65178. this._tempInfluences[influenceCount++] = target.influence;
  65179. this._supportsNormals = this._supportsNormals && target.hasNormals;
  65180. this._supportsTangents = this._supportsTangents && target.hasTangents;
  65181. if (this._vertexCount === 0) {
  65182. this._vertexCount = target.getPositions().length / 3;
  65183. }
  65184. }
  65185. }
  65186. if (!this._influences || this._influences.length !== influenceCount) {
  65187. this._influences = new Float32Array(influenceCount);
  65188. }
  65189. for (var index = 0; index < influenceCount; index++) {
  65190. this._influences[index] = this._tempInfluences[index];
  65191. }
  65192. if (needUpdate) {
  65193. // Flag meshes as dirty to resync with the active targets
  65194. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  65195. var mesh = _c[_b];
  65196. if (mesh.morphTargetManager === this) {
  65197. mesh._syncGeometryWithMorphTargetManager();
  65198. }
  65199. }
  65200. }
  65201. };
  65202. // Statics
  65203. MorphTargetManager.Parse = function (serializationObject, scene) {
  65204. var result = new MorphTargetManager(scene);
  65205. result._uniqueId = serializationObject.id;
  65206. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  65207. var targetData = _a[_i];
  65208. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  65209. }
  65210. return result;
  65211. };
  65212. return MorphTargetManager;
  65213. }());
  65214. BABYLON.MorphTargetManager = MorphTargetManager;
  65215. })(BABYLON || (BABYLON = {}));
  65216. //# sourceMappingURL=babylon.morphTargetManager.js.map
  65217. var BABYLON;
  65218. (function (BABYLON) {
  65219. /**
  65220. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  65221. * It can help converting any input color in a desired output one. This can then be used to create effects
  65222. * from sepia, black and white to sixties or futuristic rendering...
  65223. *
  65224. * The only supported format is currently 3dl.
  65225. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  65226. */
  65227. var ColorGradingTexture = (function (_super) {
  65228. __extends(ColorGradingTexture, _super);
  65229. /**
  65230. * Instantiates a ColorGradingTexture from the following parameters.
  65231. *
  65232. * @param url The location of the color gradind data (currently only supporting 3dl)
  65233. * @param scene The scene the texture will be used in
  65234. */
  65235. function ColorGradingTexture(url, scene) {
  65236. var _this = _super.call(this, scene) || this;
  65237. if (!url) {
  65238. return _this;
  65239. }
  65240. _this._textureMatrix = BABYLON.Matrix.Identity();
  65241. _this.name = url;
  65242. _this.url = url;
  65243. _this.hasAlpha = false;
  65244. _this.isCube = false;
  65245. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65246. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65247. _this.anisotropicFilteringLevel = 1;
  65248. _this._texture = _this._getFromCache(url, true);
  65249. if (!_this._texture) {
  65250. if (!scene.useDelayedTextureLoading) {
  65251. _this.loadTexture();
  65252. }
  65253. else {
  65254. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65255. }
  65256. }
  65257. return _this;
  65258. }
  65259. /**
  65260. * Returns the texture matrix used in most of the material.
  65261. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  65262. */
  65263. ColorGradingTexture.prototype.getTextureMatrix = function () {
  65264. return this._textureMatrix;
  65265. };
  65266. /**
  65267. * Occurs when the file being loaded is a .3dl LUT file.
  65268. */
  65269. ColorGradingTexture.prototype.load3dlTexture = function () {
  65270. var _this = this;
  65271. var mipLevels = 0;
  65272. var floatArrayView = null;
  65273. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65274. this._texture = texture;
  65275. var callback = function (text) {
  65276. var data;
  65277. var tempData;
  65278. var line;
  65279. var lines = text.split('\n');
  65280. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  65281. var maxColor = 0;
  65282. for (var i = 0; i < lines.length; i++) {
  65283. line = lines[i];
  65284. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  65285. continue;
  65286. if (line.indexOf('#') === 0)
  65287. continue;
  65288. var words = line.split(" ");
  65289. if (size === 0) {
  65290. // Number of space + one
  65291. size = words.length;
  65292. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  65293. tempData = new Float32Array(size * size * size * 4);
  65294. continue;
  65295. }
  65296. if (size != 0) {
  65297. var r = Math.max(parseInt(words[0]), 0);
  65298. var g = Math.max(parseInt(words[1]), 0);
  65299. var b = Math.max(parseInt(words[2]), 0);
  65300. maxColor = Math.max(r, maxColor);
  65301. maxColor = Math.max(g, maxColor);
  65302. maxColor = Math.max(b, maxColor);
  65303. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  65304. tempData[pixelStorageIndex + 0] = r;
  65305. tempData[pixelStorageIndex + 1] = g;
  65306. tempData[pixelStorageIndex + 2] = b;
  65307. pixelIndexSlice++;
  65308. if (pixelIndexSlice % size == 0) {
  65309. pixelIndexH++;
  65310. pixelIndexSlice = 0;
  65311. if (pixelIndexH % size == 0) {
  65312. pixelIndexW++;
  65313. pixelIndexH = 0;
  65314. }
  65315. }
  65316. }
  65317. }
  65318. for (var i = 0; i < tempData.length; i++) {
  65319. if (i > 0 && (i + 1) % 4 === 0) {
  65320. data[i] = 255;
  65321. }
  65322. else {
  65323. var value = tempData[i];
  65324. data[i] = (value / maxColor * 255);
  65325. }
  65326. }
  65327. texture.updateSize(size * size, size);
  65328. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  65329. };
  65330. BABYLON.Tools.LoadFile(this.url, callback);
  65331. return this._texture;
  65332. };
  65333. /**
  65334. * Starts the loading process of the texture.
  65335. */
  65336. ColorGradingTexture.prototype.loadTexture = function () {
  65337. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  65338. this.load3dlTexture();
  65339. }
  65340. };
  65341. /**
  65342. * Clones the color gradind texture.
  65343. */
  65344. ColorGradingTexture.prototype.clone = function () {
  65345. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  65346. // Base texture
  65347. newTexture.level = this.level;
  65348. return newTexture;
  65349. };
  65350. /**
  65351. * Called during delayed load for textures.
  65352. */
  65353. ColorGradingTexture.prototype.delayLoad = function () {
  65354. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  65355. return;
  65356. }
  65357. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  65358. this._texture = this._getFromCache(this.url, true);
  65359. if (!this._texture) {
  65360. this.loadTexture();
  65361. }
  65362. };
  65363. /**
  65364. * Parses a color grading texture serialized by Babylon.
  65365. * @param parsedTexture The texture information being parsedTexture
  65366. * @param scene The scene to load the texture in
  65367. * @param rootUrl The root url of the data assets to load
  65368. * @return A color gradind texture
  65369. */
  65370. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  65371. var texture = null;
  65372. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  65373. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  65374. texture.name = parsedTexture.name;
  65375. texture.level = parsedTexture.level;
  65376. }
  65377. return texture;
  65378. };
  65379. /**
  65380. * Serializes the LUT texture to json format.
  65381. */
  65382. ColorGradingTexture.prototype.serialize = function () {
  65383. if (!this.name) {
  65384. return null;
  65385. }
  65386. var serializationObject = {};
  65387. serializationObject.name = this.name;
  65388. serializationObject.level = this.level;
  65389. serializationObject.customType = "BABYLON.ColorGradingTexture";
  65390. return serializationObject;
  65391. };
  65392. return ColorGradingTexture;
  65393. }(BABYLON.BaseTexture));
  65394. /**
  65395. * Empty line regex stored for GC.
  65396. */
  65397. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  65398. BABYLON.ColorGradingTexture = ColorGradingTexture;
  65399. })(BABYLON || (BABYLON = {}));
  65400. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  65401. var BABYLON;
  65402. (function (BABYLON) {
  65403. /**
  65404. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  65405. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  65406. * 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;
  65407. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  65408. */
  65409. var ColorCurves = (function () {
  65410. function ColorCurves() {
  65411. this._dirty = true;
  65412. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  65413. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  65414. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  65415. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  65416. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  65417. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  65418. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  65419. this._globalHue = 30;
  65420. this._globalDensity = 0;
  65421. this._globalSaturation = 0;
  65422. this._globalExposure = 0;
  65423. this._highlightsHue = 30;
  65424. this._highlightsDensity = 0;
  65425. this._highlightsSaturation = 0;
  65426. this._highlightsExposure = 0;
  65427. this._midtonesHue = 30;
  65428. this._midtonesDensity = 0;
  65429. this._midtonesSaturation = 0;
  65430. this._midtonesExposure = 0;
  65431. this._shadowsHue = 30;
  65432. this._shadowsDensity = 0;
  65433. this._shadowsSaturation = 0;
  65434. this._shadowsExposure = 0;
  65435. }
  65436. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  65437. /**
  65438. * Gets the global Hue value.
  65439. * 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).
  65440. */
  65441. get: function () {
  65442. return this._globalHue;
  65443. },
  65444. /**
  65445. * Sets the global Hue value.
  65446. * 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).
  65447. */
  65448. set: function (value) {
  65449. this._globalHue = value;
  65450. this._dirty = true;
  65451. },
  65452. enumerable: true,
  65453. configurable: true
  65454. });
  65455. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  65456. /**
  65457. * Gets the global Density value.
  65458. * 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.
  65459. * Values less than zero provide a filter of opposite hue.
  65460. */
  65461. get: function () {
  65462. return this._globalDensity;
  65463. },
  65464. /**
  65465. * Sets the global Density value.
  65466. * 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.
  65467. * Values less than zero provide a filter of opposite hue.
  65468. */
  65469. set: function (value) {
  65470. this._globalDensity = value;
  65471. this._dirty = true;
  65472. },
  65473. enumerable: true,
  65474. configurable: true
  65475. });
  65476. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  65477. /**
  65478. * Gets the global Saturation value.
  65479. * 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.
  65480. */
  65481. get: function () {
  65482. return this._globalSaturation;
  65483. },
  65484. /**
  65485. * Sets the global Saturation value.
  65486. * 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.
  65487. */
  65488. set: function (value) {
  65489. this._globalSaturation = value;
  65490. this._dirty = true;
  65491. },
  65492. enumerable: true,
  65493. configurable: true
  65494. });
  65495. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  65496. /**
  65497. * Gets the highlights Hue value.
  65498. * 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).
  65499. */
  65500. get: function () {
  65501. return this._highlightsHue;
  65502. },
  65503. /**
  65504. * Sets the highlights Hue value.
  65505. * 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).
  65506. */
  65507. set: function (value) {
  65508. this._highlightsHue = value;
  65509. this._dirty = true;
  65510. },
  65511. enumerable: true,
  65512. configurable: true
  65513. });
  65514. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  65515. /**
  65516. * Gets the highlights Density value.
  65517. * 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.
  65518. * Values less than zero provide a filter of opposite hue.
  65519. */
  65520. get: function () {
  65521. return this._highlightsDensity;
  65522. },
  65523. /**
  65524. * Sets the highlights Density value.
  65525. * 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.
  65526. * Values less than zero provide a filter of opposite hue.
  65527. */
  65528. set: function (value) {
  65529. this._highlightsDensity = value;
  65530. this._dirty = true;
  65531. },
  65532. enumerable: true,
  65533. configurable: true
  65534. });
  65535. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  65536. /**
  65537. * Gets the highlights Saturation value.
  65538. * 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.
  65539. */
  65540. get: function () {
  65541. return this._highlightsSaturation;
  65542. },
  65543. /**
  65544. * Sets the highlights Saturation value.
  65545. * 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.
  65546. */
  65547. set: function (value) {
  65548. this._highlightsSaturation = value;
  65549. this._dirty = true;
  65550. },
  65551. enumerable: true,
  65552. configurable: true
  65553. });
  65554. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  65555. /**
  65556. * Gets the highlights Exposure value.
  65557. * 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.
  65558. */
  65559. get: function () {
  65560. return this._highlightsExposure;
  65561. },
  65562. /**
  65563. * Sets the highlights Exposure value.
  65564. * 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.
  65565. */
  65566. set: function (value) {
  65567. this._highlightsExposure = value;
  65568. this._dirty = true;
  65569. },
  65570. enumerable: true,
  65571. configurable: true
  65572. });
  65573. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  65574. /**
  65575. * Gets the midtones Hue value.
  65576. * 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).
  65577. */
  65578. get: function () {
  65579. return this._midtonesHue;
  65580. },
  65581. /**
  65582. * Sets the midtones Hue value.
  65583. * 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).
  65584. */
  65585. set: function (value) {
  65586. this._midtonesHue = value;
  65587. this._dirty = true;
  65588. },
  65589. enumerable: true,
  65590. configurable: true
  65591. });
  65592. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  65593. /**
  65594. * Gets the midtones Density value.
  65595. * 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.
  65596. * Values less than zero provide a filter of opposite hue.
  65597. */
  65598. get: function () {
  65599. return this._midtonesDensity;
  65600. },
  65601. /**
  65602. * Sets the midtones Density value.
  65603. * 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.
  65604. * Values less than zero provide a filter of opposite hue.
  65605. */
  65606. set: function (value) {
  65607. this._midtonesDensity = value;
  65608. this._dirty = true;
  65609. },
  65610. enumerable: true,
  65611. configurable: true
  65612. });
  65613. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  65614. /**
  65615. * Gets the midtones Saturation value.
  65616. * 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.
  65617. */
  65618. get: function () {
  65619. return this._midtonesSaturation;
  65620. },
  65621. /**
  65622. * Sets the midtones Saturation value.
  65623. * 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.
  65624. */
  65625. set: function (value) {
  65626. this._midtonesSaturation = value;
  65627. this._dirty = true;
  65628. },
  65629. enumerable: true,
  65630. configurable: true
  65631. });
  65632. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  65633. /**
  65634. * Gets the midtones Exposure value.
  65635. * 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.
  65636. */
  65637. get: function () {
  65638. return this._midtonesExposure;
  65639. },
  65640. /**
  65641. * Sets the midtones Exposure value.
  65642. * 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.
  65643. */
  65644. set: function (value) {
  65645. this._midtonesExposure = value;
  65646. this._dirty = true;
  65647. },
  65648. enumerable: true,
  65649. configurable: true
  65650. });
  65651. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  65652. /**
  65653. * Gets the shadows Hue value.
  65654. * 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).
  65655. */
  65656. get: function () {
  65657. return this._shadowsHue;
  65658. },
  65659. /**
  65660. * Sets the shadows Hue value.
  65661. * 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).
  65662. */
  65663. set: function (value) {
  65664. this._shadowsHue = value;
  65665. this._dirty = true;
  65666. },
  65667. enumerable: true,
  65668. configurable: true
  65669. });
  65670. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  65671. /**
  65672. * Gets the shadows Density value.
  65673. * 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.
  65674. * Values less than zero provide a filter of opposite hue.
  65675. */
  65676. get: function () {
  65677. return this._shadowsDensity;
  65678. },
  65679. /**
  65680. * Sets the shadows Density value.
  65681. * 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.
  65682. * Values less than zero provide a filter of opposite hue.
  65683. */
  65684. set: function (value) {
  65685. this._shadowsDensity = value;
  65686. this._dirty = true;
  65687. },
  65688. enumerable: true,
  65689. configurable: true
  65690. });
  65691. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  65692. /**
  65693. * Gets the shadows Saturation value.
  65694. * 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.
  65695. */
  65696. get: function () {
  65697. return this._shadowsSaturation;
  65698. },
  65699. /**
  65700. * Sets the shadows Saturation value.
  65701. * 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.
  65702. */
  65703. set: function (value) {
  65704. this._shadowsSaturation = value;
  65705. this._dirty = true;
  65706. },
  65707. enumerable: true,
  65708. configurable: true
  65709. });
  65710. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  65711. /**
  65712. * Gets the shadows Exposure value.
  65713. * 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.
  65714. */
  65715. get: function () {
  65716. return this._shadowsExposure;
  65717. },
  65718. /**
  65719. * Sets the shadows Exposure value.
  65720. * 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.
  65721. */
  65722. set: function (value) {
  65723. this._shadowsExposure = value;
  65724. this._dirty = true;
  65725. },
  65726. enumerable: true,
  65727. configurable: true
  65728. });
  65729. ColorCurves.prototype.getClassName = function () {
  65730. return "ColorCurves";
  65731. };
  65732. /**
  65733. * Binds the color curves to the shader.
  65734. * @param colorCurves The color curve to bind
  65735. * @param effect The effect to bind to
  65736. */
  65737. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  65738. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  65739. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  65740. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  65741. if (colorCurves._dirty) {
  65742. colorCurves._dirty = false;
  65743. // Fill in global info.
  65744. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  65745. // Compute highlights info.
  65746. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  65747. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  65748. // Compute midtones info.
  65749. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  65750. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  65751. // Compute shadows info.
  65752. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  65753. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  65754. // Compute deltas (neutral is midtones).
  65755. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  65756. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  65757. }
  65758. if (effect) {
  65759. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  65760. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  65761. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  65762. }
  65763. };
  65764. /**
  65765. * Prepare the list of uniforms associated with the ColorCurves effects.
  65766. * @param uniformsList The list of uniforms used in the effect
  65767. */
  65768. ColorCurves.PrepareUniforms = function (uniformsList) {
  65769. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  65770. };
  65771. /**
  65772. * Returns color grading data based on a hue, density, saturation and exposure value.
  65773. * @param filterHue The hue of the color filter.
  65774. * @param filterDensity The density of the color filter.
  65775. * @param saturation The saturation.
  65776. * @param exposure The exposure.
  65777. * @param result The result data container.
  65778. */
  65779. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  65780. if (hue == null) {
  65781. return;
  65782. }
  65783. hue = ColorCurves.clamp(hue, 0, 360);
  65784. density = ColorCurves.clamp(density, -100, 100);
  65785. saturation = ColorCurves.clamp(saturation, -100, 100);
  65786. exposure = ColorCurves.clamp(exposure, -100, 100);
  65787. // Remap the slider/config filter density with non-linear mapping and also scale by half
  65788. // so that the maximum filter density is only 50% control. This provides fine control
  65789. // for small values and reasonable range.
  65790. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  65791. density *= 0.5;
  65792. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  65793. if (density < 0) {
  65794. density *= -1;
  65795. hue = (hue + 180) % 360;
  65796. }
  65797. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  65798. result.scaleToRef(2, result);
  65799. result.a = 1 + 0.01 * saturation;
  65800. };
  65801. /**
  65802. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  65803. * @param value The input slider value in range [-100,100].
  65804. * @returns Adjusted value.
  65805. */
  65806. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  65807. value /= 100;
  65808. var x = Math.abs(value);
  65809. x = Math.pow(x, 2);
  65810. if (value < 0) {
  65811. x *= -1;
  65812. }
  65813. x *= 100;
  65814. return x;
  65815. };
  65816. /**
  65817. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  65818. * @param hue The hue (H) input.
  65819. * @param saturation The saturation (S) input.
  65820. * @param brightness The brightness (B) input.
  65821. * @result An RGBA color represented as Vector4.
  65822. */
  65823. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  65824. var h = ColorCurves.clamp(hue, 0, 360);
  65825. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  65826. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  65827. if (s === 0) {
  65828. result.r = v;
  65829. result.g = v;
  65830. result.b = v;
  65831. }
  65832. else {
  65833. // sector 0 to 5
  65834. h /= 60;
  65835. var i = Math.floor(h);
  65836. // fractional part of h
  65837. var f = h - i;
  65838. var p = v * (1 - s);
  65839. var q = v * (1 - s * f);
  65840. var t = v * (1 - s * (1 - f));
  65841. switch (i) {
  65842. case 0:
  65843. result.r = v;
  65844. result.g = t;
  65845. result.b = p;
  65846. break;
  65847. case 1:
  65848. result.r = q;
  65849. result.g = v;
  65850. result.b = p;
  65851. break;
  65852. case 2:
  65853. result.r = p;
  65854. result.g = v;
  65855. result.b = t;
  65856. break;
  65857. case 3:
  65858. result.r = p;
  65859. result.g = q;
  65860. result.b = v;
  65861. break;
  65862. case 4:
  65863. result.r = t;
  65864. result.g = p;
  65865. result.b = v;
  65866. break;
  65867. default:
  65868. result.r = v;
  65869. result.g = p;
  65870. result.b = q;
  65871. break;
  65872. }
  65873. }
  65874. result.a = 1;
  65875. };
  65876. /**
  65877. * Returns a value clamped between min and max
  65878. * @param value The value to clamp
  65879. * @param min The minimum of value
  65880. * @param max The maximum of value
  65881. * @returns The clamped value.
  65882. */
  65883. ColorCurves.clamp = function (value, min, max) {
  65884. return Math.min(Math.max(value, min), max);
  65885. };
  65886. /**
  65887. * Clones the current color curve instance.
  65888. * @return The cloned curves
  65889. */
  65890. ColorCurves.prototype.clone = function () {
  65891. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  65892. };
  65893. /**
  65894. * Serializes the current color curve instance to a json representation.
  65895. * @return a JSON representation
  65896. */
  65897. ColorCurves.prototype.serialize = function () {
  65898. return BABYLON.SerializationHelper.Serialize(this);
  65899. };
  65900. /**
  65901. * Parses the color curve from a json representation.
  65902. * @param source the JSON source to parse
  65903. * @return The parsed curves
  65904. */
  65905. ColorCurves.Parse = function (source) {
  65906. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  65907. };
  65908. return ColorCurves;
  65909. }());
  65910. __decorate([
  65911. BABYLON.serialize()
  65912. ], ColorCurves.prototype, "_globalHue", void 0);
  65913. __decorate([
  65914. BABYLON.serialize()
  65915. ], ColorCurves.prototype, "_globalDensity", void 0);
  65916. __decorate([
  65917. BABYLON.serialize()
  65918. ], ColorCurves.prototype, "_globalSaturation", void 0);
  65919. __decorate([
  65920. BABYLON.serialize()
  65921. ], ColorCurves.prototype, "_globalExposure", void 0);
  65922. __decorate([
  65923. BABYLON.serialize()
  65924. ], ColorCurves.prototype, "_highlightsHue", void 0);
  65925. __decorate([
  65926. BABYLON.serialize()
  65927. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  65928. __decorate([
  65929. BABYLON.serialize()
  65930. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  65931. __decorate([
  65932. BABYLON.serialize()
  65933. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  65934. __decorate([
  65935. BABYLON.serialize()
  65936. ], ColorCurves.prototype, "_midtonesHue", void 0);
  65937. __decorate([
  65938. BABYLON.serialize()
  65939. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  65940. __decorate([
  65941. BABYLON.serialize()
  65942. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  65943. __decorate([
  65944. BABYLON.serialize()
  65945. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  65946. BABYLON.ColorCurves = ColorCurves;
  65947. })(BABYLON || (BABYLON = {}));
  65948. //# sourceMappingURL=babylon.colorCurves.js.map
  65949. var BABYLON;
  65950. (function (BABYLON) {
  65951. var Octree = (function () {
  65952. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  65953. if (maxDepth === void 0) { maxDepth = 2; }
  65954. this.maxDepth = maxDepth;
  65955. this.dynamicContent = new Array();
  65956. this._maxBlockCapacity = maxBlockCapacity || 64;
  65957. this._selectionContent = new BABYLON.SmartArray(1024);
  65958. this._creationFunc = creationFunc;
  65959. }
  65960. // Methods
  65961. Octree.prototype.update = function (worldMin, worldMax, entries) {
  65962. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  65963. };
  65964. Octree.prototype.addMesh = function (entry) {
  65965. for (var index = 0; index < this.blocks.length; index++) {
  65966. var block = this.blocks[index];
  65967. block.addEntry(entry);
  65968. }
  65969. };
  65970. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  65971. this._selectionContent.reset();
  65972. for (var index = 0; index < this.blocks.length; index++) {
  65973. var block = this.blocks[index];
  65974. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  65975. }
  65976. if (allowDuplicate) {
  65977. this._selectionContent.concat(this.dynamicContent);
  65978. }
  65979. else {
  65980. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  65981. }
  65982. return this._selectionContent;
  65983. };
  65984. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  65985. this._selectionContent.reset();
  65986. for (var index = 0; index < this.blocks.length; index++) {
  65987. var block = this.blocks[index];
  65988. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  65989. }
  65990. if (allowDuplicate) {
  65991. this._selectionContent.concat(this.dynamicContent);
  65992. }
  65993. else {
  65994. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  65995. }
  65996. return this._selectionContent;
  65997. };
  65998. Octree.prototype.intersectsRay = function (ray) {
  65999. this._selectionContent.reset();
  66000. for (var index = 0; index < this.blocks.length; index++) {
  66001. var block = this.blocks[index];
  66002. block.intersectsRay(ray, this._selectionContent);
  66003. }
  66004. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  66005. return this._selectionContent;
  66006. };
  66007. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  66008. target.blocks = new Array();
  66009. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  66010. // Segmenting space
  66011. for (var x = 0; x < 2; x++) {
  66012. for (var y = 0; y < 2; y++) {
  66013. for (var z = 0; z < 2; z++) {
  66014. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  66015. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  66016. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  66017. block.addEntries(entries);
  66018. target.blocks.push(block);
  66019. }
  66020. }
  66021. }
  66022. };
  66023. return Octree;
  66024. }());
  66025. Octree.CreationFuncForMeshes = function (entry, block) {
  66026. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  66027. block.entries.push(entry);
  66028. }
  66029. };
  66030. Octree.CreationFuncForSubMeshes = function (entry, block) {
  66031. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  66032. block.entries.push(entry);
  66033. }
  66034. };
  66035. BABYLON.Octree = Octree;
  66036. })(BABYLON || (BABYLON = {}));
  66037. //# sourceMappingURL=babylon.octree.js.map
  66038. var BABYLON;
  66039. (function (BABYLON) {
  66040. var OctreeBlock = (function () {
  66041. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  66042. this.entries = new Array();
  66043. this._boundingVectors = new Array();
  66044. this._capacity = capacity;
  66045. this._depth = depth;
  66046. this._maxDepth = maxDepth;
  66047. this._creationFunc = creationFunc;
  66048. this._minPoint = minPoint;
  66049. this._maxPoint = maxPoint;
  66050. this._boundingVectors.push(minPoint.clone());
  66051. this._boundingVectors.push(maxPoint.clone());
  66052. this._boundingVectors.push(minPoint.clone());
  66053. this._boundingVectors[2].x = maxPoint.x;
  66054. this._boundingVectors.push(minPoint.clone());
  66055. this._boundingVectors[3].y = maxPoint.y;
  66056. this._boundingVectors.push(minPoint.clone());
  66057. this._boundingVectors[4].z = maxPoint.z;
  66058. this._boundingVectors.push(maxPoint.clone());
  66059. this._boundingVectors[5].z = minPoint.z;
  66060. this._boundingVectors.push(maxPoint.clone());
  66061. this._boundingVectors[6].x = minPoint.x;
  66062. this._boundingVectors.push(maxPoint.clone());
  66063. this._boundingVectors[7].y = minPoint.y;
  66064. }
  66065. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  66066. // Property
  66067. get: function () {
  66068. return this._capacity;
  66069. },
  66070. enumerable: true,
  66071. configurable: true
  66072. });
  66073. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  66074. get: function () {
  66075. return this._minPoint;
  66076. },
  66077. enumerable: true,
  66078. configurable: true
  66079. });
  66080. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  66081. get: function () {
  66082. return this._maxPoint;
  66083. },
  66084. enumerable: true,
  66085. configurable: true
  66086. });
  66087. // Methods
  66088. OctreeBlock.prototype.addEntry = function (entry) {
  66089. if (this.blocks) {
  66090. for (var index = 0; index < this.blocks.length; index++) {
  66091. var block = this.blocks[index];
  66092. block.addEntry(entry);
  66093. }
  66094. return;
  66095. }
  66096. this._creationFunc(entry, this);
  66097. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  66098. this.createInnerBlocks();
  66099. }
  66100. };
  66101. OctreeBlock.prototype.addEntries = function (entries) {
  66102. for (var index = 0; index < entries.length; index++) {
  66103. var mesh = entries[index];
  66104. this.addEntry(mesh);
  66105. }
  66106. };
  66107. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  66108. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  66109. if (this.blocks) {
  66110. for (var index = 0; index < this.blocks.length; index++) {
  66111. var block = this.blocks[index];
  66112. block.select(frustumPlanes, selection, allowDuplicate);
  66113. }
  66114. return;
  66115. }
  66116. if (allowDuplicate) {
  66117. selection.concat(this.entries);
  66118. }
  66119. else {
  66120. selection.concatWithNoDuplicate(this.entries);
  66121. }
  66122. }
  66123. };
  66124. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  66125. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  66126. if (this.blocks) {
  66127. for (var index = 0; index < this.blocks.length; index++) {
  66128. var block = this.blocks[index];
  66129. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  66130. }
  66131. return;
  66132. }
  66133. if (allowDuplicate) {
  66134. selection.concat(this.entries);
  66135. }
  66136. else {
  66137. selection.concatWithNoDuplicate(this.entries);
  66138. }
  66139. }
  66140. };
  66141. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  66142. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  66143. if (this.blocks) {
  66144. for (var index = 0; index < this.blocks.length; index++) {
  66145. var block = this.blocks[index];
  66146. block.intersectsRay(ray, selection);
  66147. }
  66148. return;
  66149. }
  66150. selection.concatWithNoDuplicate(this.entries);
  66151. }
  66152. };
  66153. OctreeBlock.prototype.createInnerBlocks = function () {
  66154. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  66155. };
  66156. return OctreeBlock;
  66157. }());
  66158. BABYLON.OctreeBlock = OctreeBlock;
  66159. })(BABYLON || (BABYLON = {}));
  66160. //# sourceMappingURL=babylon.octreeBlock.js.map
  66161. var BABYLON;
  66162. (function (BABYLON) {
  66163. var SIMDVector3 = (function () {
  66164. function SIMDVector3() {
  66165. }
  66166. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  66167. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  66168. };
  66169. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  66170. var m = transformation.m;
  66171. var m0 = SIMD.Float32x4.load(m, 0);
  66172. var m1 = SIMD.Float32x4.load(m, 4);
  66173. var m2 = SIMD.Float32x4.load(m, 8);
  66174. var m3 = SIMD.Float32x4.load(m, 12);
  66175. 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));
  66176. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  66177. result.x = SIMD.Float32x4.extractLane(r, 0);
  66178. result.y = SIMD.Float32x4.extractLane(r, 1);
  66179. result.z = SIMD.Float32x4.extractLane(r, 2);
  66180. };
  66181. return SIMDVector3;
  66182. }());
  66183. var SIMDMatrix = (function () {
  66184. function SIMDMatrix() {
  66185. }
  66186. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  66187. var tm = this.m;
  66188. var om = other.m;
  66189. var m0 = SIMD.Float32x4.load(om, 0);
  66190. var m1 = SIMD.Float32x4.load(om, 4);
  66191. var m2 = SIMD.Float32x4.load(om, 8);
  66192. var m3 = SIMD.Float32x4.load(om, 12);
  66193. for (var i = 0; i < 16; i += 4) {
  66194. 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)))));
  66195. }
  66196. return this;
  66197. };
  66198. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  66199. var src = this.m;
  66200. var dest = other.m;
  66201. // Load the 4 rows
  66202. var src0 = SIMD.Float32x4.load(src, 0);
  66203. var src1 = SIMD.Float32x4.load(src, 4);
  66204. var src2 = SIMD.Float32x4.load(src, 8);
  66205. var src3 = SIMD.Float32x4.load(src, 12);
  66206. // Transpose the source matrix. Sort of. Not a true transpose operation
  66207. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  66208. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  66209. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  66210. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  66211. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  66212. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  66213. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  66214. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  66215. // This is a true transposition, but it will lead to an incorrect result
  66216. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  66217. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  66218. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  66219. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  66220. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  66221. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  66222. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  66223. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  66224. // ----
  66225. tmp1 = SIMD.Float32x4.mul(row2, row3);
  66226. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66227. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  66228. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  66229. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66230. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  66231. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  66232. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  66233. // ----
  66234. tmp1 = SIMD.Float32x4.mul(row1, row2);
  66235. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66236. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  66237. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  66238. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66239. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  66240. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  66241. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  66242. // ----
  66243. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  66244. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66245. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  66246. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  66247. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  66248. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66249. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  66250. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  66251. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  66252. // ----
  66253. tmp1 = SIMD.Float32x4.mul(row0, row1);
  66254. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66255. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  66256. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  66257. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66258. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  66259. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  66260. // ----
  66261. tmp1 = SIMD.Float32x4.mul(row0, row3);
  66262. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66263. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  66264. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  66265. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66266. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  66267. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  66268. // ----
  66269. tmp1 = SIMD.Float32x4.mul(row0, row2);
  66270. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66271. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  66272. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  66273. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66274. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  66275. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  66276. // Compute determinant
  66277. var det = SIMD.Float32x4.mul(row0, minor0);
  66278. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  66279. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  66280. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  66281. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  66282. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  66283. // These shuffles aren't necessary if the faulty transposition is done
  66284. // up at the top of this function.
  66285. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  66286. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  66287. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  66288. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  66289. // Compute final values by multiplying with 1/det
  66290. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  66291. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  66292. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  66293. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  66294. return this;
  66295. };
  66296. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  66297. var out = result.m;
  66298. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  66299. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  66300. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  66301. // cc.kmVec3Subtract(f, pCenter, pEye);
  66302. var f = SIMD.Float32x4.sub(center, eye);
  66303. // cc.kmVec3Normalize(f, f);
  66304. var tmp = SIMD.Float32x4.mul(f, f);
  66305. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  66306. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  66307. // cc.kmVec3Assign(up, pUp);
  66308. // cc.kmVec3Normalize(up, up);
  66309. tmp = SIMD.Float32x4.mul(up, up);
  66310. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  66311. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  66312. // cc.kmVec3Cross(s, f, up);
  66313. 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)));
  66314. // cc.kmVec3Normalize(s, s);
  66315. tmp = SIMD.Float32x4.mul(s, s);
  66316. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  66317. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  66318. // cc.kmVec3Cross(u, s, f);
  66319. 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)));
  66320. // cc.kmVec3Normalize(s, s);
  66321. tmp = SIMD.Float32x4.mul(s, s);
  66322. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  66323. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  66324. var zero = SIMD.Float32x4.splat(0.0);
  66325. s = SIMD.Float32x4.neg(s);
  66326. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  66327. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  66328. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  66329. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  66330. 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);
  66331. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  66332. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  66333. 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)))));
  66334. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  66335. 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)))));
  66336. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  66337. 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)))));
  66338. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  66339. 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)))));
  66340. };
  66341. return SIMDMatrix;
  66342. }());
  66343. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  66344. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  66345. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  66346. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  66347. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  66348. var SIMDHelper = (function () {
  66349. function SIMDHelper() {
  66350. }
  66351. Object.defineProperty(SIMDHelper, "IsEnabled", {
  66352. get: function () {
  66353. return SIMDHelper._isEnabled;
  66354. },
  66355. enumerable: true,
  66356. configurable: true
  66357. });
  66358. SIMDHelper.DisableSIMD = function () {
  66359. // Replace functions
  66360. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  66361. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  66362. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  66363. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  66364. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  66365. SIMDHelper._isEnabled = false;
  66366. };
  66367. SIMDHelper.EnableSIMD = function () {
  66368. if (self.SIMD === undefined) {
  66369. return;
  66370. }
  66371. // check if polyfills needed
  66372. if (!self.Math.fround) {
  66373. self.Math.fround = (function (array) { return function (x) {
  66374. return array[0] = x, array[0];
  66375. }; })(new Float32Array(1));
  66376. }
  66377. if (!self.Math.imul) {
  66378. self.Math.imul = function (a, b) {
  66379. var ah = (a >>> 16) & 0xffff;
  66380. var al = a & 0xffff;
  66381. var bh = (b >>> 16) & 0xffff;
  66382. var bl = b & 0xffff;
  66383. // the shift by 0 fixes the sign on the high part
  66384. // the final |0 converts the unsigned value into a signed value
  66385. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  66386. };
  66387. }
  66388. // Replace functions
  66389. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  66390. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  66391. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  66392. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  66393. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  66394. SIMDHelper._isEnabled = true;
  66395. };
  66396. return SIMDHelper;
  66397. }());
  66398. SIMDHelper._isEnabled = false;
  66399. BABYLON.SIMDHelper = SIMDHelper;
  66400. })(BABYLON || (BABYLON = {}));
  66401. //# sourceMappingURL=babylon.math.SIMD.js.map
  66402. var BABYLON;
  66403. (function (BABYLON) {
  66404. var VRDistortionCorrectionPostProcess = (function (_super) {
  66405. __extends(VRDistortionCorrectionPostProcess, _super);
  66406. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  66407. var _this = _super.call(this, name, "vrDistortionCorrection", [
  66408. 'LensCenter',
  66409. 'Scale',
  66410. 'ScaleIn',
  66411. 'HmdWarpParam'
  66412. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  66413. _this._isRightEye = isRightEye;
  66414. _this._distortionFactors = vrMetrics.distortionK;
  66415. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  66416. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  66417. _this.adaptScaleToCurrentViewport = true;
  66418. _this.onSizeChangedObservable.add(function () {
  66419. _this.aspectRatio = _this.width * .5 / _this.height;
  66420. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  66421. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  66422. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  66423. });
  66424. _this.onApplyObservable.add(function (effect) {
  66425. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  66426. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  66427. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  66428. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  66429. });
  66430. return _this;
  66431. }
  66432. return VRDistortionCorrectionPostProcess;
  66433. }(BABYLON.PostProcess));
  66434. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  66435. })(BABYLON || (BABYLON = {}));
  66436. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  66437. var BABYLON;
  66438. (function (BABYLON) {
  66439. var AnaglyphPostProcess = (function (_super) {
  66440. __extends(AnaglyphPostProcess, _super);
  66441. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  66442. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  66443. _this._passedProcess = rigCameras[0]._rigPostProcess;
  66444. _this.onApplyObservable.add(function (effect) {
  66445. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  66446. });
  66447. return _this;
  66448. }
  66449. return AnaglyphPostProcess;
  66450. }(BABYLON.PostProcess));
  66451. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  66452. })(BABYLON || (BABYLON = {}));
  66453. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  66454. var BABYLON;
  66455. (function (BABYLON) {
  66456. var StereoscopicInterlacePostProcess = (function (_super) {
  66457. __extends(StereoscopicInterlacePostProcess, _super);
  66458. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  66459. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  66460. _this._passedProcess = rigCameras[0]._rigPostProcess;
  66461. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  66462. _this.onSizeChangedObservable.add(function () {
  66463. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  66464. });
  66465. _this.onApplyObservable.add(function (effect) {
  66466. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  66467. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  66468. });
  66469. return _this;
  66470. }
  66471. return StereoscopicInterlacePostProcess;
  66472. }(BABYLON.PostProcess));
  66473. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  66474. })(BABYLON || (BABYLON = {}));
  66475. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  66476. var BABYLON;
  66477. (function (BABYLON) {
  66478. var FreeCameraDeviceOrientationInput = (function () {
  66479. function FreeCameraDeviceOrientationInput() {
  66480. var _this = this;
  66481. this._screenOrientationAngle = 0;
  66482. this._screenQuaternion = new BABYLON.Quaternion();
  66483. this._alpha = 0;
  66484. this._beta = 0;
  66485. this._gamma = 0;
  66486. this._orientationChanged = function () {
  66487. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  66488. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  66489. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  66490. };
  66491. this._deviceOrientation = function (evt) {
  66492. _this._alpha = evt.alpha;
  66493. _this._beta = evt.beta;
  66494. _this._gamma = evt.gamma;
  66495. };
  66496. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  66497. this._orientationChanged();
  66498. }
  66499. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  66500. get: function () {
  66501. return this._camera;
  66502. },
  66503. set: function (camera) {
  66504. this._camera = camera;
  66505. if (this._camera != null && !this._camera.rotationQuaternion) {
  66506. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  66507. }
  66508. },
  66509. enumerable: true,
  66510. configurable: true
  66511. });
  66512. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  66513. window.addEventListener("orientationchange", this._orientationChanged);
  66514. window.addEventListener("deviceorientation", this._deviceOrientation);
  66515. //In certain cases, the attach control is called AFTER orientation was changed,
  66516. //So this is needed.
  66517. this._orientationChanged();
  66518. };
  66519. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  66520. window.removeEventListener("orientationchange", this._orientationChanged);
  66521. window.removeEventListener("deviceorientation", this._deviceOrientation);
  66522. };
  66523. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  66524. //if no device orientation provided, don't update the rotation.
  66525. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  66526. if (!this._alpha)
  66527. return;
  66528. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  66529. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  66530. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  66531. //Mirror on XY Plane
  66532. this._camera.rotationQuaternion.z *= -1;
  66533. this._camera.rotationQuaternion.w *= -1;
  66534. };
  66535. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  66536. return "FreeCameraDeviceOrientationInput";
  66537. };
  66538. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  66539. return "deviceOrientation";
  66540. };
  66541. return FreeCameraDeviceOrientationInput;
  66542. }());
  66543. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  66544. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  66545. })(BABYLON || (BABYLON = {}));
  66546. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  66547. var BABYLON;
  66548. (function (BABYLON) {
  66549. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  66550. function ArcRotateCameraVRDeviceOrientationInput() {
  66551. this.alphaCorrection = 1;
  66552. this.betaCorrection = 1;
  66553. this.gammaCorrection = 1;
  66554. this._alpha = 0;
  66555. this._beta = 0;
  66556. this._gamma = 0;
  66557. this._dirty = false;
  66558. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  66559. }
  66560. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  66561. this.camera.attachControl(element, noPreventDefault);
  66562. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  66563. };
  66564. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  66565. var camera = this.camera;
  66566. this._alpha = +evt.alpha | 0;
  66567. this._beta = +evt.beta | 0;
  66568. this._gamma = +evt.gamma | 0;
  66569. this._dirty = true;
  66570. };
  66571. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  66572. if (this._dirty) {
  66573. this._dirty = false;
  66574. if (this._gamma < 0) {
  66575. this._gamma = 180 + this._gamma;
  66576. }
  66577. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  66578. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  66579. }
  66580. };
  66581. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  66582. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  66583. };
  66584. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  66585. return "ArcRotateCameraVRDeviceOrientationInput";
  66586. };
  66587. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  66588. return "VRDeviceOrientation";
  66589. };
  66590. return ArcRotateCameraVRDeviceOrientationInput;
  66591. }());
  66592. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  66593. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  66594. })(BABYLON || (BABYLON = {}));
  66595. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  66596. var BABYLON;
  66597. (function (BABYLON) {
  66598. var VRCameraMetrics = (function () {
  66599. function VRCameraMetrics() {
  66600. this.compensateDistortion = true;
  66601. }
  66602. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  66603. get: function () {
  66604. return this.hResolution / (2 * this.vResolution);
  66605. },
  66606. enumerable: true,
  66607. configurable: true
  66608. });
  66609. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  66610. get: function () {
  66611. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  66612. },
  66613. enumerable: true,
  66614. configurable: true
  66615. });
  66616. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  66617. get: function () {
  66618. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  66619. var h = (4 * meters) / this.hScreenSize;
  66620. return BABYLON.Matrix.Translation(h, 0, 0);
  66621. },
  66622. enumerable: true,
  66623. configurable: true
  66624. });
  66625. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  66626. get: function () {
  66627. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  66628. var h = (4 * meters) / this.hScreenSize;
  66629. return BABYLON.Matrix.Translation(-h, 0, 0);
  66630. },
  66631. enumerable: true,
  66632. configurable: true
  66633. });
  66634. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  66635. get: function () {
  66636. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  66637. },
  66638. enumerable: true,
  66639. configurable: true
  66640. });
  66641. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  66642. get: function () {
  66643. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  66644. },
  66645. enumerable: true,
  66646. configurable: true
  66647. });
  66648. VRCameraMetrics.GetDefault = function () {
  66649. var result = new VRCameraMetrics();
  66650. result.hResolution = 1280;
  66651. result.vResolution = 800;
  66652. result.hScreenSize = 0.149759993;
  66653. result.vScreenSize = 0.0935999975;
  66654. result.vScreenCenter = 0.0467999987;
  66655. result.eyeToScreenDistance = 0.0410000011;
  66656. result.lensSeparationDistance = 0.0635000020;
  66657. result.interpupillaryDistance = 0.0640000030;
  66658. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  66659. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  66660. result.postProcessScaleFactor = 1.714605507808412;
  66661. result.lensCenterOffset = 0.151976421;
  66662. return result;
  66663. };
  66664. return VRCameraMetrics;
  66665. }());
  66666. BABYLON.VRCameraMetrics = VRCameraMetrics;
  66667. })(BABYLON || (BABYLON = {}));
  66668. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  66669. var BABYLON;
  66670. (function (BABYLON) {
  66671. var WebVRFreeCamera = (function (_super) {
  66672. __extends(WebVRFreeCamera, _super);
  66673. function WebVRFreeCamera(name, position, scene, webVROptions) {
  66674. if (webVROptions === void 0) { webVROptions = {}; }
  66675. var _this = _super.call(this, name, position, scene) || this;
  66676. _this.webVROptions = webVROptions;
  66677. _this._vrDevice = null;
  66678. _this.rawPose = null;
  66679. _this._specsVersion = "1.1";
  66680. _this._attached = false;
  66681. _this._positionOffset = BABYLON.Vector3.Zero();
  66682. _this._descendants = [];
  66683. _this.devicePosition = BABYLON.Vector3.Zero();
  66684. _this.deviceScaleFactor = 1;
  66685. _this.controllers = [];
  66686. _this.onControllersAttachedObservable = new BABYLON.Observable();
  66687. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  66688. _this.minZ = 0.1;
  66689. //legacy support - the compensation boolean was removed.
  66690. if (arguments.length === 5) {
  66691. _this.webVROptions = arguments[4];
  66692. }
  66693. // default webVR options
  66694. if (_this.webVROptions.trackPosition == undefined) {
  66695. _this.webVROptions.trackPosition = true;
  66696. }
  66697. if (_this.webVROptions.controllerMeshes == undefined) {
  66698. _this.webVROptions.controllerMeshes = true;
  66699. }
  66700. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  66701. _this.webVROptions.defaultLightingOnControllers = true;
  66702. }
  66703. _this.rotationQuaternion = new BABYLON.Quaternion();
  66704. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66705. if (_this.webVROptions && _this.webVROptions.positionScale) {
  66706. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  66707. }
  66708. //enable VR
  66709. var engine = _this.getEngine();
  66710. _this._onVREnabled = function (success) { if (success) {
  66711. _this.initControllers();
  66712. } };
  66713. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  66714. engine.initWebVR().add(function (event) {
  66715. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  66716. return;
  66717. }
  66718. _this._vrDevice = event.vrDisplay;
  66719. //reset the rig parameters.
  66720. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  66721. if (_this._attached) {
  66722. _this.getEngine().enableVR();
  66723. }
  66724. });
  66725. if (typeof (VRFrameData) !== "undefined")
  66726. _this._frameData = new VRFrameData();
  66727. /**
  66728. * The idea behind the following lines:
  66729. * objects that have the camera as parent should actually have the rig cameras as a parent.
  66730. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  66731. * the second will not show it correctly.
  66732. *
  66733. * To solve this - each object that has the camera as parent will be added to a protected array.
  66734. * When the rig camera renders, it will take this array and set all of those to be its children.
  66735. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  66736. * Amazing!
  66737. */
  66738. scene.onBeforeCameraRenderObservable.add(function (camera) {
  66739. if (camera.parent === _this && _this.rigParenting) {
  66740. _this._descendants = _this.getDescendants(true, function (n) {
  66741. // don't take the cameras or the controllers!
  66742. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  66743. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  66744. return !isController && !isRigCamera;
  66745. });
  66746. _this._descendants.forEach(function (node) {
  66747. node.parent = camera;
  66748. });
  66749. }
  66750. });
  66751. scene.onAfterCameraRenderObservable.add(function (camera) {
  66752. if (camera.parent === _this && _this.rigParenting) {
  66753. _this._descendants.forEach(function (node) {
  66754. node.parent = _this;
  66755. });
  66756. }
  66757. });
  66758. return _this;
  66759. }
  66760. WebVRFreeCamera.prototype.dispose = function () {
  66761. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  66762. _super.prototype.dispose.call(this);
  66763. };
  66764. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  66765. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  66766. var gp = _a[_i];
  66767. if (gp.hand === name) {
  66768. return gp;
  66769. }
  66770. }
  66771. return undefined;
  66772. };
  66773. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  66774. get: function () {
  66775. if (!this._leftController) {
  66776. this._leftController = this.getControllerByName("left");
  66777. }
  66778. return this._leftController;
  66779. },
  66780. enumerable: true,
  66781. configurable: true
  66782. });
  66783. ;
  66784. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  66785. get: function () {
  66786. if (!this._rightController) {
  66787. this._rightController = this.getControllerByName("right");
  66788. }
  66789. return this._rightController;
  66790. },
  66791. enumerable: true,
  66792. configurable: true
  66793. });
  66794. ;
  66795. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  66796. if (length === void 0) { length = 100; }
  66797. if (this.leftCamera) {
  66798. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  66799. }
  66800. else {
  66801. return _super.prototype.getForwardRay.call(this, length);
  66802. }
  66803. };
  66804. WebVRFreeCamera.prototype._checkInputs = function () {
  66805. if (this._vrDevice && this._vrDevice.isPresenting) {
  66806. this._vrDevice.getFrameData(this._frameData);
  66807. this.updateFromDevice(this._frameData.pose);
  66808. }
  66809. _super.prototype._checkInputs.call(this);
  66810. };
  66811. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  66812. if (poseData && poseData.orientation) {
  66813. this.rawPose = poseData;
  66814. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  66815. if (this.getScene().useRightHandedSystem) {
  66816. this.deviceRotationQuaternion.z *= -1;
  66817. this.deviceRotationQuaternion.w *= -1;
  66818. }
  66819. if (this.webVROptions.trackPosition && this.rawPose.position) {
  66820. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  66821. if (this.getScene().useRightHandedSystem) {
  66822. this.devicePosition.z *= -1;
  66823. }
  66824. }
  66825. }
  66826. };
  66827. /**
  66828. * WebVR's attach control will start broadcasting frames to the device.
  66829. * Note that in certain browsers (chrome for example) this function must be called
  66830. * within a user-interaction callback. Example:
  66831. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  66832. *
  66833. * @param {HTMLElement} element
  66834. * @param {boolean} [noPreventDefault]
  66835. *
  66836. * @memberOf WebVRFreeCamera
  66837. */
  66838. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  66839. _super.prototype.attachControl.call(this, element, noPreventDefault);
  66840. this._attached = true;
  66841. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  66842. if (this._vrDevice) {
  66843. this.getEngine().enableVR();
  66844. }
  66845. };
  66846. WebVRFreeCamera.prototype.detachControl = function (element) {
  66847. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  66848. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  66849. _super.prototype.detachControl.call(this, element);
  66850. this._attached = false;
  66851. this.getEngine().disableVR();
  66852. };
  66853. WebVRFreeCamera.prototype.getClassName = function () {
  66854. return "WebVRFreeCamera";
  66855. };
  66856. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  66857. //uses the vrDisplay's "resetPose()".
  66858. //pitch and roll won't be affected.
  66859. this._vrDevice.resetPose();
  66860. };
  66861. WebVRFreeCamera.prototype._updateRigCameras = function () {
  66862. var camLeft = this._rigCameras[0];
  66863. var camRight = this._rigCameras[1];
  66864. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66865. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66866. camLeft.position.copyFrom(this.devicePosition);
  66867. camRight.position.copyFrom(this.devicePosition);
  66868. };
  66869. /**
  66870. * This function is called by the two RIG cameras.
  66871. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  66872. */
  66873. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  66874. var _this = this;
  66875. //WebVR 1.1
  66876. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  66877. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  66878. if (!this.getScene().useRightHandedSystem) {
  66879. [2, 6, 8, 9, 14].forEach(function (num) {
  66880. _this._webvrViewMatrix.m[num] *= -1;
  66881. });
  66882. }
  66883. // update the camera rotation matrix
  66884. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  66885. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  66886. // Computing target and final matrix
  66887. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  66888. var parentCamera = this._cameraRigParams["parentCamera"];
  66889. // should the view matrix be updated with scale and position offset?
  66890. if (parentCamera.deviceScaleFactor !== 1) {
  66891. this._webvrViewMatrix.invert();
  66892. // scale the position, if set
  66893. if (parentCamera.deviceScaleFactor) {
  66894. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  66895. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  66896. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  66897. }
  66898. this._webvrViewMatrix.invert();
  66899. }
  66900. return this._webvrViewMatrix;
  66901. };
  66902. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  66903. var _this = this;
  66904. var parentCamera = this.parent;
  66905. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  66906. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  66907. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  66908. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  66909. //babylon compatible matrix
  66910. if (!this.getScene().useRightHandedSystem) {
  66911. [8, 9, 10, 11].forEach(function (num) {
  66912. _this._projectionMatrix.m[num] *= -1;
  66913. });
  66914. }
  66915. return this._projectionMatrix;
  66916. };
  66917. WebVRFreeCamera.prototype.initControllers = function () {
  66918. var _this = this;
  66919. this.controllers = [];
  66920. var manager = this.getScene().gamepadManager;
  66921. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  66922. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  66923. var webVrController = gamepad;
  66924. if (webVrController.defaultModel) {
  66925. webVrController.defaultModel.setEnabled(false);
  66926. }
  66927. }
  66928. });
  66929. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  66930. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  66931. var webVrController = gamepad;
  66932. if (_this.webVROptions.controllerMeshes) {
  66933. if (webVrController.defaultModel) {
  66934. webVrController.defaultModel.setEnabled(true);
  66935. }
  66936. else {
  66937. // Load the meshes
  66938. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  66939. if (_this.webVROptions.defaultLightingOnControllers) {
  66940. if (!_this._lightOnControllers) {
  66941. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  66942. }
  66943. var activateLightOnSubMeshes_1 = function (mesh, light) {
  66944. var children = mesh.getChildren();
  66945. if (children.length !== 0) {
  66946. children.forEach(function (mesh) {
  66947. light.includedOnlyMeshes.push(mesh);
  66948. activateLightOnSubMeshes_1(mesh, light);
  66949. });
  66950. }
  66951. };
  66952. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  66953. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  66954. }
  66955. });
  66956. }
  66957. }
  66958. webVrController.attachToPoseControlledCamera(_this);
  66959. // since this is async - sanity check. Is the controller already stored?
  66960. if (_this.controllers.indexOf(webVrController) === -1) {
  66961. //add to the controllers array
  66962. _this.controllers.push(webVrController);
  66963. //did we find enough controllers? Great! let the developer know.
  66964. if (_this.controllers.length >= 2) {
  66965. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  66966. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  66967. // So we're overriding setting left & right manually to be sure
  66968. var firstViveWandDetected = false;
  66969. for (var i = 0; i < _this.controllers.length; i++) {
  66970. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  66971. if (!firstViveWandDetected) {
  66972. firstViveWandDetected = true;
  66973. _this.controllers[i].hand = "left";
  66974. }
  66975. else {
  66976. _this.controllers[i].hand = "right";
  66977. }
  66978. }
  66979. }
  66980. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  66981. }
  66982. }
  66983. }
  66984. });
  66985. };
  66986. return WebVRFreeCamera;
  66987. }(BABYLON.FreeCamera));
  66988. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  66989. })(BABYLON || (BABYLON = {}));
  66990. //# sourceMappingURL=babylon.webVRCamera.js.map
  66991. /// <reference path="babylon.freeCamera.ts" />
  66992. var BABYLON;
  66993. (function (BABYLON) {
  66994. // We're mainly based on the logic defined into the FreeCamera code
  66995. var DeviceOrientationCamera = (function (_super) {
  66996. __extends(DeviceOrientationCamera, _super);
  66997. function DeviceOrientationCamera(name, position, scene) {
  66998. var _this = _super.call(this, name, position, scene) || this;
  66999. _this._quaternionCache = new BABYLON.Quaternion();
  67000. _this.inputs.addDeviceOrientation();
  67001. return _this;
  67002. }
  67003. DeviceOrientationCamera.prototype.getClassName = function () {
  67004. return "DeviceOrientationCamera";
  67005. };
  67006. DeviceOrientationCamera.prototype._checkInputs = function () {
  67007. _super.prototype._checkInputs.call(this);
  67008. this._quaternionCache.copyFrom(this.rotationQuaternion);
  67009. if (this._initialQuaternion) {
  67010. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  67011. }
  67012. };
  67013. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  67014. var _this = this;
  67015. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  67016. //can only work if this camera has a rotation quaternion already.
  67017. if (!this.rotationQuaternion)
  67018. return;
  67019. if (!this._initialQuaternion) {
  67020. this._initialQuaternion = new BABYLON.Quaternion();
  67021. }
  67022. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  67023. ['x', 'y', 'z'].forEach(function (axisName) {
  67024. if (!axis[axisName]) {
  67025. _this._initialQuaternion[axisName] = 0;
  67026. }
  67027. else {
  67028. _this._initialQuaternion[axisName] *= -1;
  67029. }
  67030. });
  67031. this._initialQuaternion.normalize();
  67032. //force rotation update
  67033. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  67034. };
  67035. return DeviceOrientationCamera;
  67036. }(BABYLON.FreeCamera));
  67037. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  67038. })(BABYLON || (BABYLON = {}));
  67039. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  67040. var BABYLON;
  67041. (function (BABYLON) {
  67042. var VRDeviceOrientationFreeCamera = (function (_super) {
  67043. __extends(VRDeviceOrientationFreeCamera, _super);
  67044. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  67045. if (compensateDistortion === void 0) { compensateDistortion = true; }
  67046. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  67047. var _this = _super.call(this, name, position, scene) || this;
  67048. vrCameraMetrics.compensateDistortion = compensateDistortion;
  67049. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  67050. return _this;
  67051. }
  67052. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  67053. return "VRDeviceOrientationFreeCamera";
  67054. };
  67055. return VRDeviceOrientationFreeCamera;
  67056. }(BABYLON.DeviceOrientationCamera));
  67057. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  67058. var VRDeviceOrientationGamepadCamera = (function (_super) {
  67059. __extends(VRDeviceOrientationGamepadCamera, _super);
  67060. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  67061. if (compensateDistortion === void 0) { compensateDistortion = true; }
  67062. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  67063. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  67064. _this.inputs.addGamepad();
  67065. return _this;
  67066. }
  67067. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  67068. return "VRDeviceOrientationGamepadCamera";
  67069. };
  67070. return VRDeviceOrientationGamepadCamera;
  67071. }(VRDeviceOrientationFreeCamera));
  67072. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  67073. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  67074. __extends(VRDeviceOrientationArcRotateCamera, _super);
  67075. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  67076. if (compensateDistortion === void 0) { compensateDistortion = true; }
  67077. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  67078. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  67079. vrCameraMetrics.compensateDistortion = compensateDistortion;
  67080. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  67081. _this.inputs.addVRDeviceOrientation();
  67082. return _this;
  67083. }
  67084. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  67085. return "VRDeviceOrientationArcRotateCamera";
  67086. };
  67087. return VRDeviceOrientationArcRotateCamera;
  67088. }(BABYLON.ArcRotateCamera));
  67089. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  67090. })(BABYLON || (BABYLON = {}));
  67091. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  67092. /// <reference path="babylon.freeCamera.ts" />
  67093. /// <reference path="babylon.arcRotateCamera.ts" />
  67094. /// <reference path="babylon.gamepadCamera.ts" />
  67095. /// <reference path="babylon.universalCamera.ts" />
  67096. var BABYLON;
  67097. (function (BABYLON) {
  67098. var AnaglyphFreeCamera = (function (_super) {
  67099. __extends(AnaglyphFreeCamera, _super);
  67100. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  67101. var _this = _super.call(this, name, position, scene) || this;
  67102. _this.interaxialDistance = interaxialDistance;
  67103. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67104. return _this;
  67105. }
  67106. AnaglyphFreeCamera.prototype.getClassName = function () {
  67107. return "AnaglyphFreeCamera";
  67108. };
  67109. return AnaglyphFreeCamera;
  67110. }(BABYLON.FreeCamera));
  67111. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  67112. var AnaglyphArcRotateCamera = (function (_super) {
  67113. __extends(AnaglyphArcRotateCamera, _super);
  67114. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  67115. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  67116. _this.interaxialDistance = interaxialDistance;
  67117. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67118. return _this;
  67119. }
  67120. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  67121. return "AnaglyphArcRotateCamera";
  67122. };
  67123. return AnaglyphArcRotateCamera;
  67124. }(BABYLON.ArcRotateCamera));
  67125. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  67126. var AnaglyphGamepadCamera = (function (_super) {
  67127. __extends(AnaglyphGamepadCamera, _super);
  67128. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  67129. var _this = _super.call(this, name, position, scene) || this;
  67130. _this.interaxialDistance = interaxialDistance;
  67131. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67132. return _this;
  67133. }
  67134. AnaglyphGamepadCamera.prototype.getClassName = function () {
  67135. return "AnaglyphGamepadCamera";
  67136. };
  67137. return AnaglyphGamepadCamera;
  67138. }(BABYLON.GamepadCamera));
  67139. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  67140. var AnaglyphUniversalCamera = (function (_super) {
  67141. __extends(AnaglyphUniversalCamera, _super);
  67142. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  67143. var _this = _super.call(this, name, position, scene) || this;
  67144. _this.interaxialDistance = interaxialDistance;
  67145. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67146. return _this;
  67147. }
  67148. AnaglyphUniversalCamera.prototype.getClassName = function () {
  67149. return "AnaglyphUniversalCamera";
  67150. };
  67151. return AnaglyphUniversalCamera;
  67152. }(BABYLON.UniversalCamera));
  67153. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  67154. var StereoscopicFreeCamera = (function (_super) {
  67155. __extends(StereoscopicFreeCamera, _super);
  67156. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  67157. var _this = _super.call(this, name, position, scene) || this;
  67158. _this.interaxialDistance = interaxialDistance;
  67159. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67160. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67161. return _this;
  67162. }
  67163. StereoscopicFreeCamera.prototype.getClassName = function () {
  67164. return "StereoscopicFreeCamera";
  67165. };
  67166. return StereoscopicFreeCamera;
  67167. }(BABYLON.FreeCamera));
  67168. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  67169. var StereoscopicArcRotateCamera = (function (_super) {
  67170. __extends(StereoscopicArcRotateCamera, _super);
  67171. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  67172. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  67173. _this.interaxialDistance = interaxialDistance;
  67174. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67175. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67176. return _this;
  67177. }
  67178. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  67179. return "StereoscopicArcRotateCamera";
  67180. };
  67181. return StereoscopicArcRotateCamera;
  67182. }(BABYLON.ArcRotateCamera));
  67183. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  67184. var StereoscopicGamepadCamera = (function (_super) {
  67185. __extends(StereoscopicGamepadCamera, _super);
  67186. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  67187. var _this = _super.call(this, name, position, scene) || this;
  67188. _this.interaxialDistance = interaxialDistance;
  67189. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67190. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67191. return _this;
  67192. }
  67193. StereoscopicGamepadCamera.prototype.getClassName = function () {
  67194. return "StereoscopicGamepadCamera";
  67195. };
  67196. return StereoscopicGamepadCamera;
  67197. }(BABYLON.GamepadCamera));
  67198. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  67199. var StereoscopicUniversalCamera = (function (_super) {
  67200. __extends(StereoscopicUniversalCamera, _super);
  67201. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  67202. var _this = _super.call(this, name, position, scene) || this;
  67203. _this.interaxialDistance = interaxialDistance;
  67204. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67205. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67206. return _this;
  67207. }
  67208. StereoscopicUniversalCamera.prototype.getClassName = function () {
  67209. return "StereoscopicUniversalCamera";
  67210. };
  67211. return StereoscopicUniversalCamera;
  67212. }(BABYLON.UniversalCamera));
  67213. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  67214. })(BABYLON || (BABYLON = {}));
  67215. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  67216. var BABYLON;
  67217. (function (BABYLON) {
  67218. var VRExperienceHelper = (function () {
  67219. function VRExperienceHelper(scene, webVROptions) {
  67220. if (webVROptions === void 0) { webVROptions = {}; }
  67221. var _this = this;
  67222. this.webVROptions = webVROptions;
  67223. // Can the system support WebVR, even if a headset isn't plugged in?
  67224. this._webVRsupported = false;
  67225. // If WebVR is supported, is a headset plugged in and are we ready to present?
  67226. this._webVRready = false;
  67227. // Are we waiting for the requestPresent callback to complete?
  67228. this._webVRrequesting = false;
  67229. // Are we presenting to the headset right now?
  67230. this._webVRpresenting = false;
  67231. // Are we presenting in the fullscreen fallback?
  67232. this._fullscreenVRpresenting = false;
  67233. this._scene = scene;
  67234. if (!this._scene.activeCamera) {
  67235. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  67236. }
  67237. else {
  67238. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  67239. if (scene.activeCamera.rotation) {
  67240. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  67241. }
  67242. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  67243. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  67244. }
  67245. this._scene.activeCamera = this._deviceOrientationCamera;
  67246. this._position = this._scene.activeCamera.position;
  67247. this._canvas = scene.getEngine().getRenderingCanvas();
  67248. this._scene.activeCamera.attachControl(this._canvas);
  67249. this._btnVR = document.createElement("BUTTON");
  67250. this._btnVR.className = "babylonVRicon";
  67251. this._btnVR.id = "babylonVRiconbtn";
  67252. this._btnVR.title = "Click to switch to VR";
  67253. 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) }";
  67254. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  67255. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  67256. // css += ".babylonVRicon.vrdisplaysupported { }";
  67257. // css += ".babylonVRicon.vrdisplayready { }";
  67258. // css += ".babylonVRicon.vrdisplayrequesting { }";
  67259. var style = document.createElement('style');
  67260. style.appendChild(document.createTextNode(css));
  67261. document.getElementsByTagName('head')[0].appendChild(style);
  67262. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  67263. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  67264. this._btnVR.addEventListener("click", function () {
  67265. _this.enterVR();
  67266. });
  67267. window.addEventListener("resize", function () {
  67268. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  67269. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  67270. if (_this._fullscreenVRpresenting) {
  67271. _this.exitVR();
  67272. }
  67273. });
  67274. document.body.appendChild(this._btnVR);
  67275. // Exiting VR mode using 'ESC' key on desktop
  67276. this._onKeyDown = function (event) {
  67277. if (event.keyCode === 27 && _this.isInVRMode()) {
  67278. _this.exitVR();
  67279. }
  67280. };
  67281. document.addEventListener("keydown", this._onKeyDown);
  67282. // Exiting VR mode double tapping the touch screen
  67283. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  67284. if (_this.isInVRMode()) {
  67285. _this.exitVR();
  67286. }
  67287. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  67288. // Listen for WebVR display changes
  67289. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  67290. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  67291. this._onVRRequestPresentStart = function () {
  67292. _this._webVRrequesting = true;
  67293. _this.updateButtonVisibility();
  67294. };
  67295. this._onVRRequestPresentComplete = function (success) {
  67296. _this._webVRrequesting = false;
  67297. _this.updateButtonVisibility();
  67298. };
  67299. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  67300. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  67301. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  67302. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  67303. // Create the cameras
  67304. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  67305. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene);
  67306. this.updateButtonVisibility();
  67307. }
  67308. VRExperienceHelper.prototype.isInVRMode = function () {
  67309. return this._webVRpresenting || this._fullscreenVRpresenting;
  67310. };
  67311. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  67312. var vrDisplay = this._scene.getEngine().getVRDevice();
  67313. if (vrDisplay) {
  67314. var wasPresenting = this._webVRpresenting;
  67315. // A VR display is connected
  67316. this._webVRpresenting = vrDisplay.isPresenting;
  67317. if (wasPresenting && !this._webVRpresenting)
  67318. this.exitVR();
  67319. }
  67320. else {
  67321. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  67322. }
  67323. this.updateButtonVisibility();
  67324. };
  67325. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  67326. this._webVRsupported = eventArgs.vrSupported;
  67327. this._webVRready = !!eventArgs.vrDisplay;
  67328. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  67329. this.updateButtonVisibility();
  67330. };
  67331. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  67332. if (!this._btnVR) {
  67333. return;
  67334. }
  67335. this._btnVR.className = "babylonVRicon";
  67336. if (this.isInVRMode()) {
  67337. this._btnVR.className += " vrdisplaypresenting";
  67338. }
  67339. else {
  67340. if (this._webVRready)
  67341. this._btnVR.className += " vrdisplayready";
  67342. if (this._webVRsupported)
  67343. this._btnVR.className += " vrdisplaysupported";
  67344. if (this._webVRrequesting)
  67345. this._btnVR.className += " vrdisplayrequesting";
  67346. }
  67347. };
  67348. /**
  67349. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  67350. * Otherwise, will use the fullscreen API.
  67351. */
  67352. VRExperienceHelper.prototype.enterVR = function () {
  67353. if (this._webVRrequesting)
  67354. return;
  67355. // If WebVR is supported and a headset is connected
  67356. if (this._webVRready) {
  67357. if (!this._webVRpresenting) {
  67358. this._webVRCamera.position = this._position;
  67359. this._scene.activeCamera = this._webVRCamera;
  67360. }
  67361. }
  67362. else {
  67363. this._vrDeviceOrientationCamera.position = this._position;
  67364. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  67365. this._scene.getEngine().switchFullscreen(true);
  67366. this._fullscreenVRpresenting = true;
  67367. this.updateButtonVisibility();
  67368. }
  67369. this._scene.activeCamera.attachControl(this._canvas);
  67370. };
  67371. /**
  67372. * Attempt to exit VR, or fullscreen.
  67373. */
  67374. VRExperienceHelper.prototype.exitVR = function () {
  67375. if (this._webVRpresenting) {
  67376. this._scene.getEngine().disableVR();
  67377. }
  67378. if (this._scene.activeCamera) {
  67379. this._position = this._scene.activeCamera.position;
  67380. }
  67381. this._deviceOrientationCamera.position = this._position;
  67382. this._scene.activeCamera = this._deviceOrientationCamera;
  67383. this._scene.activeCamera.attachControl(this._canvas);
  67384. this._fullscreenVRpresenting = false;
  67385. this.updateButtonVisibility();
  67386. };
  67387. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  67388. get: function () {
  67389. return this._position;
  67390. },
  67391. set: function (value) {
  67392. this._position = value;
  67393. this._scene.activeCamera.position = value;
  67394. },
  67395. enumerable: true,
  67396. configurable: true
  67397. });
  67398. VRExperienceHelper.prototype.dispose = function () {
  67399. if (this.isInVRMode()) {
  67400. this.exitVR();
  67401. }
  67402. this._deviceOrientationCamera.dispose();
  67403. if (this._webVRCamera) {
  67404. this._webVRCamera.dispose();
  67405. }
  67406. if (this._vrDeviceOrientationCamera) {
  67407. this._vrDeviceOrientationCamera.dispose();
  67408. }
  67409. document.body.removeChild(this._btnVR);
  67410. document.removeEventListener("keydown", this._onKeyDown);
  67411. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  67412. };
  67413. VRExperienceHelper.prototype.getClassName = function () {
  67414. return "VRExperienceHelper";
  67415. };
  67416. return VRExperienceHelper;
  67417. }());
  67418. BABYLON.VRExperienceHelper = VRExperienceHelper;
  67419. })(BABYLON || (BABYLON = {}));
  67420. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  67421. // Mainly based on these 2 articles :
  67422. // 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
  67423. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  67424. var BABYLON;
  67425. (function (BABYLON) {
  67426. var JoystickAxis;
  67427. (function (JoystickAxis) {
  67428. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  67429. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  67430. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  67431. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  67432. var VirtualJoystick = (function () {
  67433. function VirtualJoystick(leftJoystick) {
  67434. var _this = this;
  67435. if (leftJoystick) {
  67436. this._leftJoystick = true;
  67437. }
  67438. else {
  67439. this._leftJoystick = false;
  67440. }
  67441. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  67442. VirtualJoystick._globalJoystickIndex++;
  67443. // By default left & right arrow keys are moving the X
  67444. // and up & down keys are moving the Y
  67445. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  67446. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  67447. this.reverseLeftRight = false;
  67448. this.reverseUpDown = false;
  67449. // collections of pointers
  67450. this._touches = new BABYLON.StringDictionary();
  67451. this.deltaPosition = BABYLON.Vector3.Zero();
  67452. this._joystickSensibility = 25;
  67453. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  67454. this._rotationSpeed = 25;
  67455. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  67456. this._rotateOnAxisRelativeToMesh = false;
  67457. this._onResize = function (evt) {
  67458. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  67459. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  67460. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  67461. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  67462. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  67463. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  67464. };
  67465. // injecting a canvas element on top of the canvas 3D game
  67466. if (!VirtualJoystick.vjCanvas) {
  67467. window.addEventListener("resize", this._onResize, false);
  67468. VirtualJoystick.vjCanvas = document.createElement("canvas");
  67469. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  67470. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  67471. VirtualJoystick.vjCanvas.width = window.innerWidth;
  67472. VirtualJoystick.vjCanvas.height = window.innerHeight;
  67473. VirtualJoystick.vjCanvas.style.width = "100%";
  67474. VirtualJoystick.vjCanvas.style.height = "100%";
  67475. VirtualJoystick.vjCanvas.style.position = "absolute";
  67476. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  67477. VirtualJoystick.vjCanvas.style.top = "0px";
  67478. VirtualJoystick.vjCanvas.style.left = "0px";
  67479. VirtualJoystick.vjCanvas.style.zIndex = "5";
  67480. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  67481. // Support for jQuery PEP polyfill
  67482. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  67483. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  67484. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  67485. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  67486. document.body.appendChild(VirtualJoystick.vjCanvas);
  67487. }
  67488. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  67489. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  67490. this.pressed = false;
  67491. // default joystick color
  67492. this._joystickColor = "cyan";
  67493. this._joystickPointerID = -1;
  67494. // current joystick position
  67495. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  67496. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  67497. // origin joystick position
  67498. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  67499. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  67500. this._onPointerDownHandlerRef = function (evt) {
  67501. _this._onPointerDown(evt);
  67502. };
  67503. this._onPointerMoveHandlerRef = function (evt) {
  67504. _this._onPointerMove(evt);
  67505. };
  67506. this._onPointerOutHandlerRef = function (evt) {
  67507. _this._onPointerUp(evt);
  67508. };
  67509. this._onPointerUpHandlerRef = function (evt) {
  67510. _this._onPointerUp(evt);
  67511. };
  67512. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  67513. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  67514. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  67515. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  67516. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  67517. evt.preventDefault(); // Disables system menu
  67518. }, false);
  67519. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  67520. }
  67521. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  67522. this._joystickSensibility = newJoystickSensibility;
  67523. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  67524. };
  67525. VirtualJoystick.prototype._onPointerDown = function (e) {
  67526. var positionOnScreenCondition;
  67527. e.preventDefault();
  67528. if (this._leftJoystick === true) {
  67529. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  67530. }
  67531. else {
  67532. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  67533. }
  67534. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  67535. // First contact will be dedicated to the virtual joystick
  67536. this._joystickPointerID = e.pointerId;
  67537. this._joystickPointerStartPos.x = e.clientX;
  67538. this._joystickPointerStartPos.y = e.clientY;
  67539. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  67540. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  67541. this._deltaJoystickVector.x = 0;
  67542. this._deltaJoystickVector.y = 0;
  67543. this.pressed = true;
  67544. this._touches.add(e.pointerId.toString(), e);
  67545. }
  67546. else {
  67547. // You can only trigger the action buttons with a joystick declared
  67548. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  67549. this._action();
  67550. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  67551. }
  67552. }
  67553. };
  67554. VirtualJoystick.prototype._onPointerMove = function (e) {
  67555. // If the current pointer is the one associated to the joystick (first touch contact)
  67556. if (this._joystickPointerID == e.pointerId) {
  67557. this._joystickPointerPos.x = e.clientX;
  67558. this._joystickPointerPos.y = e.clientY;
  67559. this._deltaJoystickVector = this._joystickPointerPos.clone();
  67560. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  67561. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  67562. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  67563. switch (this._axisTargetedByLeftAndRight) {
  67564. case JoystickAxis.X:
  67565. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  67566. break;
  67567. case JoystickAxis.Y:
  67568. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  67569. break;
  67570. case JoystickAxis.Z:
  67571. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  67572. break;
  67573. }
  67574. var directionUpDown = this.reverseUpDown ? 1 : -1;
  67575. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  67576. switch (this._axisTargetedByUpAndDown) {
  67577. case JoystickAxis.X:
  67578. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  67579. break;
  67580. case JoystickAxis.Y:
  67581. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  67582. break;
  67583. case JoystickAxis.Z:
  67584. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  67585. break;
  67586. }
  67587. }
  67588. else {
  67589. var data = this._touches.get(e.pointerId.toString());
  67590. if (data) {
  67591. data.x = e.clientX;
  67592. data.y = e.clientY;
  67593. }
  67594. }
  67595. };
  67596. VirtualJoystick.prototype._onPointerUp = function (e) {
  67597. if (this._joystickPointerID == e.pointerId) {
  67598. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  67599. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  67600. this._joystickPointerID = -1;
  67601. this.pressed = false;
  67602. }
  67603. else {
  67604. var touch = this._touches.get(e.pointerId.toString());
  67605. if (touch) {
  67606. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  67607. }
  67608. }
  67609. this._deltaJoystickVector.x = 0;
  67610. this._deltaJoystickVector.y = 0;
  67611. this._touches.remove(e.pointerId.toString());
  67612. };
  67613. /**
  67614. * Change the color of the virtual joystick
  67615. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  67616. */
  67617. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  67618. this._joystickColor = newColor;
  67619. };
  67620. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  67621. this._action = action;
  67622. };
  67623. // Define which axis you'd like to control for left & right
  67624. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  67625. switch (axis) {
  67626. case JoystickAxis.X:
  67627. case JoystickAxis.Y:
  67628. case JoystickAxis.Z:
  67629. this._axisTargetedByLeftAndRight = axis;
  67630. break;
  67631. default:
  67632. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  67633. break;
  67634. }
  67635. };
  67636. // Define which axis you'd like to control for up & down
  67637. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  67638. switch (axis) {
  67639. case JoystickAxis.X:
  67640. case JoystickAxis.Y:
  67641. case JoystickAxis.Z:
  67642. this._axisTargetedByUpAndDown = axis;
  67643. break;
  67644. default:
  67645. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  67646. break;
  67647. }
  67648. };
  67649. VirtualJoystick.prototype._clearCanvas = function () {
  67650. if (this._leftJoystick) {
  67651. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  67652. }
  67653. else {
  67654. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  67655. }
  67656. };
  67657. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  67658. var _this = this;
  67659. if (this.pressed) {
  67660. this._touches.forEach(function (key, touch) {
  67661. if (touch.pointerId === _this._joystickPointerID) {
  67662. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  67663. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  67664. VirtualJoystick.vjCanvasContext.beginPath();
  67665. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  67666. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  67667. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  67668. VirtualJoystick.vjCanvasContext.stroke();
  67669. VirtualJoystick.vjCanvasContext.closePath();
  67670. VirtualJoystick.vjCanvasContext.beginPath();
  67671. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  67672. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  67673. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  67674. VirtualJoystick.vjCanvasContext.stroke();
  67675. VirtualJoystick.vjCanvasContext.closePath();
  67676. VirtualJoystick.vjCanvasContext.beginPath();
  67677. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  67678. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  67679. VirtualJoystick.vjCanvasContext.stroke();
  67680. VirtualJoystick.vjCanvasContext.closePath();
  67681. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  67682. }
  67683. else {
  67684. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  67685. VirtualJoystick.vjCanvasContext.beginPath();
  67686. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  67687. VirtualJoystick.vjCanvasContext.beginPath();
  67688. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  67689. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  67690. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  67691. VirtualJoystick.vjCanvasContext.stroke();
  67692. VirtualJoystick.vjCanvasContext.closePath();
  67693. touch.prevX = touch.x;
  67694. touch.prevY = touch.y;
  67695. }
  67696. ;
  67697. });
  67698. }
  67699. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  67700. };
  67701. VirtualJoystick.prototype.releaseCanvas = function () {
  67702. if (VirtualJoystick.vjCanvas) {
  67703. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  67704. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  67705. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  67706. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  67707. window.removeEventListener("resize", this._onResize);
  67708. document.body.removeChild(VirtualJoystick.vjCanvas);
  67709. VirtualJoystick.vjCanvas = null;
  67710. }
  67711. };
  67712. return VirtualJoystick;
  67713. }());
  67714. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  67715. VirtualJoystick._globalJoystickIndex = 0;
  67716. BABYLON.VirtualJoystick = VirtualJoystick;
  67717. })(BABYLON || (BABYLON = {}));
  67718. //# sourceMappingURL=babylon.virtualJoystick.js.map
  67719. var BABYLON;
  67720. (function (BABYLON) {
  67721. // We're mainly based on the logic defined into the FreeCamera code
  67722. var VirtualJoysticksCamera = (function (_super) {
  67723. __extends(VirtualJoysticksCamera, _super);
  67724. function VirtualJoysticksCamera(name, position, scene) {
  67725. var _this = _super.call(this, name, position, scene) || this;
  67726. _this.inputs.addVirtualJoystick();
  67727. return _this;
  67728. }
  67729. VirtualJoysticksCamera.prototype.getClassName = function () {
  67730. return "VirtualJoysticksCamera";
  67731. };
  67732. return VirtualJoysticksCamera;
  67733. }(BABYLON.FreeCamera));
  67734. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  67735. })(BABYLON || (BABYLON = {}));
  67736. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  67737. var BABYLON;
  67738. (function (BABYLON) {
  67739. var FreeCameraVirtualJoystickInput = (function () {
  67740. function FreeCameraVirtualJoystickInput() {
  67741. }
  67742. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  67743. return this._leftjoystick;
  67744. };
  67745. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  67746. return this._rightjoystick;
  67747. };
  67748. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  67749. if (this._leftjoystick) {
  67750. var camera = this.camera;
  67751. var speed = camera._computeLocalCameraSpeed() * 50;
  67752. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  67753. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  67754. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  67755. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  67756. if (!this._leftjoystick.pressed) {
  67757. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  67758. }
  67759. if (!this._rightjoystick.pressed) {
  67760. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  67761. }
  67762. }
  67763. };
  67764. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  67765. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  67766. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  67767. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  67768. this._leftjoystick.setJoystickSensibility(0.15);
  67769. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  67770. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  67771. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  67772. this._rightjoystick.reverseUpDown = true;
  67773. this._rightjoystick.setJoystickSensibility(0.05);
  67774. this._rightjoystick.setJoystickColor("yellow");
  67775. };
  67776. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  67777. this._leftjoystick.releaseCanvas();
  67778. this._rightjoystick.releaseCanvas();
  67779. };
  67780. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  67781. return "FreeCameraVirtualJoystickInput";
  67782. };
  67783. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  67784. return "virtualJoystick";
  67785. };
  67786. return FreeCameraVirtualJoystickInput;
  67787. }());
  67788. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  67789. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  67790. })(BABYLON || (BABYLON = {}));
  67791. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  67792. var BABYLON;
  67793. (function (BABYLON) {
  67794. var SimplificationSettings = (function () {
  67795. function SimplificationSettings(quality, distance, optimizeMesh) {
  67796. this.quality = quality;
  67797. this.distance = distance;
  67798. this.optimizeMesh = optimizeMesh;
  67799. }
  67800. return SimplificationSettings;
  67801. }());
  67802. BABYLON.SimplificationSettings = SimplificationSettings;
  67803. var SimplificationQueue = (function () {
  67804. function SimplificationQueue() {
  67805. this.running = false;
  67806. this._simplificationArray = [];
  67807. }
  67808. SimplificationQueue.prototype.addTask = function (task) {
  67809. this._simplificationArray.push(task);
  67810. };
  67811. SimplificationQueue.prototype.executeNext = function () {
  67812. var task = this._simplificationArray.pop();
  67813. if (task) {
  67814. this.running = true;
  67815. this.runSimplification(task);
  67816. }
  67817. else {
  67818. this.running = false;
  67819. }
  67820. };
  67821. SimplificationQueue.prototype.runSimplification = function (task) {
  67822. var _this = this;
  67823. if (task.parallelProcessing) {
  67824. //parallel simplifier
  67825. task.settings.forEach(function (setting) {
  67826. var simplifier = _this.getSimplifier(task);
  67827. simplifier.simplify(setting, function (newMesh) {
  67828. task.mesh.addLODLevel(setting.distance, newMesh);
  67829. newMesh.isVisible = true;
  67830. //check if it is the last
  67831. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  67832. //all done, run the success callback.
  67833. task.successCallback();
  67834. }
  67835. _this.executeNext();
  67836. });
  67837. });
  67838. }
  67839. else {
  67840. //single simplifier.
  67841. var simplifier = this.getSimplifier(task);
  67842. var runDecimation = function (setting, callback) {
  67843. simplifier.simplify(setting, function (newMesh) {
  67844. task.mesh.addLODLevel(setting.distance, newMesh);
  67845. newMesh.isVisible = true;
  67846. //run the next quality level
  67847. callback();
  67848. });
  67849. };
  67850. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  67851. runDecimation(task.settings[loop.index], function () {
  67852. loop.executeNext();
  67853. });
  67854. }, function () {
  67855. //execution ended, run the success callback.
  67856. if (task.successCallback) {
  67857. task.successCallback();
  67858. }
  67859. _this.executeNext();
  67860. });
  67861. }
  67862. };
  67863. SimplificationQueue.prototype.getSimplifier = function (task) {
  67864. switch (task.simplificationType) {
  67865. case SimplificationType.QUADRATIC:
  67866. default:
  67867. return new QuadraticErrorSimplification(task.mesh);
  67868. }
  67869. };
  67870. return SimplificationQueue;
  67871. }());
  67872. BABYLON.SimplificationQueue = SimplificationQueue;
  67873. /**
  67874. * The implemented types of simplification.
  67875. * At the moment only Quadratic Error Decimation is implemented.
  67876. */
  67877. var SimplificationType;
  67878. (function (SimplificationType) {
  67879. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  67880. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  67881. var DecimationTriangle = (function () {
  67882. function DecimationTriangle(vertices) {
  67883. this.vertices = vertices;
  67884. this.error = new Array(4);
  67885. this.deleted = false;
  67886. this.isDirty = false;
  67887. this.deletePending = false;
  67888. this.borderFactor = 0;
  67889. }
  67890. return DecimationTriangle;
  67891. }());
  67892. BABYLON.DecimationTriangle = DecimationTriangle;
  67893. var DecimationVertex = (function () {
  67894. function DecimationVertex(position, id) {
  67895. this.position = position;
  67896. this.id = id;
  67897. this.isBorder = true;
  67898. this.q = new QuadraticMatrix();
  67899. this.triangleCount = 0;
  67900. this.triangleStart = 0;
  67901. this.originalOffsets = [];
  67902. }
  67903. DecimationVertex.prototype.updatePosition = function (newPosition) {
  67904. this.position.copyFrom(newPosition);
  67905. };
  67906. return DecimationVertex;
  67907. }());
  67908. BABYLON.DecimationVertex = DecimationVertex;
  67909. var QuadraticMatrix = (function () {
  67910. function QuadraticMatrix(data) {
  67911. this.data = new Array(10);
  67912. for (var i = 0; i < 10; ++i) {
  67913. if (data && data[i]) {
  67914. this.data[i] = data[i];
  67915. }
  67916. else {
  67917. this.data[i] = 0;
  67918. }
  67919. }
  67920. }
  67921. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  67922. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  67923. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  67924. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  67925. return det;
  67926. };
  67927. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  67928. for (var i = 0; i < 10; ++i) {
  67929. this.data[i] += matrix.data[i];
  67930. }
  67931. };
  67932. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  67933. for (var i = 0; i < 10; ++i) {
  67934. this.data[i] += data[i];
  67935. }
  67936. };
  67937. QuadraticMatrix.prototype.add = function (matrix) {
  67938. var m = new QuadraticMatrix();
  67939. for (var i = 0; i < 10; ++i) {
  67940. m.data[i] = this.data[i] + matrix.data[i];
  67941. }
  67942. return m;
  67943. };
  67944. QuadraticMatrix.FromData = function (a, b, c, d) {
  67945. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  67946. };
  67947. //returning an array to avoid garbage collection
  67948. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  67949. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  67950. };
  67951. return QuadraticMatrix;
  67952. }());
  67953. BABYLON.QuadraticMatrix = QuadraticMatrix;
  67954. var Reference = (function () {
  67955. function Reference(vertexId, triangleId) {
  67956. this.vertexId = vertexId;
  67957. this.triangleId = triangleId;
  67958. }
  67959. return Reference;
  67960. }());
  67961. BABYLON.Reference = Reference;
  67962. /**
  67963. * An implementation of the Quadratic Error simplification algorithm.
  67964. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  67965. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  67966. * @author RaananW
  67967. */
  67968. var QuadraticErrorSimplification = (function () {
  67969. function QuadraticErrorSimplification(_mesh) {
  67970. this._mesh = _mesh;
  67971. this.initialized = false;
  67972. this.syncIterations = 5000;
  67973. this.aggressiveness = 7;
  67974. this.decimationIterations = 100;
  67975. this.boundingBoxEpsilon = BABYLON.Epsilon;
  67976. }
  67977. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  67978. var _this = this;
  67979. this.initDecimatedMesh();
  67980. //iterating through the submeshes array, one after the other.
  67981. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  67982. _this.initWithMesh(loop.index, function () {
  67983. _this.runDecimation(settings, loop.index, function () {
  67984. loop.executeNext();
  67985. });
  67986. }, settings.optimizeMesh);
  67987. }, function () {
  67988. setTimeout(function () {
  67989. successCallback(_this._reconstructedMesh);
  67990. }, 0);
  67991. });
  67992. };
  67993. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  67994. var _this = this;
  67995. var gCount = 0;
  67996. triangle.vertices.forEach(function (vertex) {
  67997. var count = 0;
  67998. var vPos = vertex.position;
  67999. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  68000. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  68001. ++count;
  68002. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  68003. ++count;
  68004. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  68005. ++count;
  68006. if (count > 1) {
  68007. ++gCount;
  68008. }
  68009. ;
  68010. });
  68011. if (gCount > 1) {
  68012. console.log(triangle, gCount);
  68013. }
  68014. return gCount > 1;
  68015. };
  68016. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  68017. var _this = this;
  68018. var targetCount = ~~(this.triangles.length * settings.quality);
  68019. var deletedTriangles = 0;
  68020. var triangleCount = this.triangles.length;
  68021. var iterationFunction = function (iteration, callback) {
  68022. setTimeout(function () {
  68023. if (iteration % 5 === 0) {
  68024. _this.updateMesh(iteration === 0);
  68025. }
  68026. for (var i = 0; i < _this.triangles.length; ++i) {
  68027. _this.triangles[i].isDirty = false;
  68028. }
  68029. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  68030. var trianglesIterator = function (i) {
  68031. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  68032. var t = _this.triangles[tIdx];
  68033. if (!t)
  68034. return;
  68035. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  68036. return;
  68037. }
  68038. for (var j = 0; j < 3; ++j) {
  68039. if (t.error[j] < threshold) {
  68040. var deleted0 = [];
  68041. var deleted1 = [];
  68042. var v0 = t.vertices[j];
  68043. var v1 = t.vertices[(j + 1) % 3];
  68044. if (v0.isBorder || v1.isBorder)
  68045. continue;
  68046. var p = BABYLON.Vector3.Zero();
  68047. var n = BABYLON.Vector3.Zero();
  68048. var uv = BABYLON.Vector2.Zero();
  68049. var color = new BABYLON.Color4(0, 0, 0, 1);
  68050. _this.calculateError(v0, v1, p, n, uv, color);
  68051. var delTr = [];
  68052. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  68053. continue;
  68054. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  68055. continue;
  68056. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  68057. continue;
  68058. var uniqueArray = [];
  68059. delTr.forEach(function (deletedT) {
  68060. if (uniqueArray.indexOf(deletedT) === -1) {
  68061. deletedT.deletePending = true;
  68062. uniqueArray.push(deletedT);
  68063. }
  68064. });
  68065. if (uniqueArray.length % 2 !== 0) {
  68066. continue;
  68067. }
  68068. v0.q = v1.q.add(v0.q);
  68069. v0.updatePosition(p);
  68070. var tStart = _this.references.length;
  68071. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  68072. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  68073. var tCount = _this.references.length - tStart;
  68074. if (tCount <= v0.triangleCount) {
  68075. if (tCount) {
  68076. for (var c = 0; c < tCount; c++) {
  68077. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  68078. }
  68079. }
  68080. }
  68081. else {
  68082. v0.triangleStart = tStart;
  68083. }
  68084. v0.triangleCount = tCount;
  68085. break;
  68086. }
  68087. }
  68088. };
  68089. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  68090. }, 0);
  68091. };
  68092. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  68093. if (triangleCount - deletedTriangles <= targetCount)
  68094. loop.breakLoop();
  68095. else {
  68096. iterationFunction(loop.index, function () {
  68097. loop.executeNext();
  68098. });
  68099. }
  68100. }, function () {
  68101. setTimeout(function () {
  68102. //reconstruct this part of the mesh
  68103. _this.reconstructMesh(submeshIndex);
  68104. successCallback();
  68105. }, 0);
  68106. });
  68107. };
  68108. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  68109. var _this = this;
  68110. this.vertices = [];
  68111. this.triangles = [];
  68112. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68113. var indices = this._mesh.getIndices();
  68114. var submesh = this._mesh.subMeshes[submeshIndex];
  68115. var findInVertices = function (positionToSearch) {
  68116. if (optimizeMesh) {
  68117. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  68118. if (_this.vertices[ii].position.equals(positionToSearch)) {
  68119. return _this.vertices[ii];
  68120. }
  68121. }
  68122. }
  68123. return null;
  68124. };
  68125. var vertexReferences = [];
  68126. var vertexInit = function (i) {
  68127. var offset = i + submesh.verticesStart;
  68128. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  68129. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  68130. vertex.originalOffsets.push(offset);
  68131. if (vertex.id === _this.vertices.length) {
  68132. _this.vertices.push(vertex);
  68133. }
  68134. vertexReferences.push(vertex.id);
  68135. };
  68136. //var totalVertices = mesh.getTotalVertices();
  68137. var totalVertices = submesh.verticesCount;
  68138. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  68139. var indicesInit = function (i) {
  68140. var offset = (submesh.indexStart / 3) + i;
  68141. var pos = (offset * 3);
  68142. var i0 = indices[pos + 0];
  68143. var i1 = indices[pos + 1];
  68144. var i2 = indices[pos + 2];
  68145. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  68146. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  68147. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  68148. var triangle = new DecimationTriangle([v0, v1, v2]);
  68149. triangle.originalOffset = pos;
  68150. _this.triangles.push(triangle);
  68151. };
  68152. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  68153. _this.init(callback);
  68154. });
  68155. });
  68156. };
  68157. QuadraticErrorSimplification.prototype.init = function (callback) {
  68158. var _this = this;
  68159. var triangleInit1 = function (i) {
  68160. var t = _this.triangles[i];
  68161. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  68162. for (var j = 0; j < 3; j++) {
  68163. 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))));
  68164. }
  68165. };
  68166. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  68167. var triangleInit2 = function (i) {
  68168. var t = _this.triangles[i];
  68169. for (var j = 0; j < 3; ++j) {
  68170. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  68171. }
  68172. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  68173. };
  68174. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  68175. _this.initialized = true;
  68176. callback();
  68177. });
  68178. });
  68179. };
  68180. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  68181. var newTriangles = [];
  68182. var i;
  68183. for (i = 0; i < this.vertices.length; ++i) {
  68184. this.vertices[i].triangleCount = 0;
  68185. }
  68186. var t;
  68187. var j;
  68188. for (i = 0; i < this.triangles.length; ++i) {
  68189. if (!this.triangles[i].deleted) {
  68190. t = this.triangles[i];
  68191. for (j = 0; j < 3; ++j) {
  68192. t.vertices[j].triangleCount = 1;
  68193. }
  68194. newTriangles.push(t);
  68195. }
  68196. }
  68197. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  68198. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  68199. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  68200. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  68201. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68202. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68203. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68204. var vertexCount = 0;
  68205. for (i = 0; i < this.vertices.length; ++i) {
  68206. var vertex = this.vertices[i];
  68207. vertex.id = vertexCount;
  68208. if (vertex.triangleCount) {
  68209. vertex.originalOffsets.forEach(function (originalOffset) {
  68210. newPositionData.push(vertex.position.x);
  68211. newPositionData.push(vertex.position.y);
  68212. newPositionData.push(vertex.position.z);
  68213. newNormalData.push(normalData[originalOffset * 3]);
  68214. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  68215. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  68216. if (uvs && uvs.length) {
  68217. newUVsData.push(uvs[(originalOffset * 2)]);
  68218. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  68219. }
  68220. else if (colorsData && colorsData.length) {
  68221. newColorsData.push(colorsData[(originalOffset * 4)]);
  68222. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  68223. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  68224. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  68225. }
  68226. ++vertexCount;
  68227. });
  68228. }
  68229. }
  68230. var startingIndex = this._reconstructedMesh.getTotalIndices();
  68231. var startingVertex = this._reconstructedMesh.getTotalVertices();
  68232. var submeshesArray = this._reconstructedMesh.subMeshes;
  68233. this._reconstructedMesh.subMeshes = [];
  68234. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  68235. var originalIndices = this._mesh.getIndices();
  68236. for (i = 0; i < newTriangles.length; ++i) {
  68237. t = newTriangles[i]; //now get the new referencing point for each vertex
  68238. [0, 1, 2].forEach(function (idx) {
  68239. var id = originalIndices[t.originalOffset + idx];
  68240. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  68241. if (offset < 0)
  68242. offset = 0;
  68243. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  68244. });
  68245. }
  68246. //overwriting the old vertex buffers and indices.
  68247. this._reconstructedMesh.setIndices(newIndicesArray);
  68248. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  68249. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  68250. if (newUVsData.length > 0)
  68251. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  68252. if (newColorsData.length > 0)
  68253. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  68254. //create submesh
  68255. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  68256. if (submeshIndex > 0) {
  68257. this._reconstructedMesh.subMeshes = [];
  68258. submeshesArray.forEach(function (submesh) {
  68259. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  68260. });
  68261. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  68262. }
  68263. };
  68264. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  68265. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  68266. this._reconstructedMesh.material = this._mesh.material;
  68267. this._reconstructedMesh.parent = this._mesh.parent;
  68268. this._reconstructedMesh.isVisible = false;
  68269. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  68270. };
  68271. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  68272. for (var i = 0; i < vertex1.triangleCount; ++i) {
  68273. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  68274. if (t.deleted)
  68275. continue;
  68276. var s = this.references[vertex1.triangleStart + i].vertexId;
  68277. var v1 = t.vertices[(s + 1) % 3];
  68278. var v2 = t.vertices[(s + 2) % 3];
  68279. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  68280. deletedArray[i] = true;
  68281. delTr.push(t);
  68282. continue;
  68283. }
  68284. var d1 = v1.position.subtract(point);
  68285. d1 = d1.normalize();
  68286. var d2 = v2.position.subtract(point);
  68287. d2 = d2.normalize();
  68288. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  68289. return true;
  68290. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  68291. deletedArray[i] = false;
  68292. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  68293. return true;
  68294. }
  68295. return false;
  68296. };
  68297. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  68298. var newDeleted = deletedTriangles;
  68299. for (var i = 0; i < vertex.triangleCount; ++i) {
  68300. var ref = this.references[vertex.triangleStart + i];
  68301. var t = this.triangles[ref.triangleId];
  68302. if (t.deleted)
  68303. continue;
  68304. if (deletedArray[i] && t.deletePending) {
  68305. t.deleted = true;
  68306. newDeleted++;
  68307. continue;
  68308. }
  68309. t.vertices[ref.vertexId] = origVertex;
  68310. t.isDirty = true;
  68311. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  68312. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  68313. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  68314. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  68315. this.references.push(ref);
  68316. }
  68317. return newDeleted;
  68318. };
  68319. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  68320. for (var i = 0; i < this.vertices.length; ++i) {
  68321. var vCount = [];
  68322. var vId = [];
  68323. var v = this.vertices[i];
  68324. var j;
  68325. for (j = 0; j < v.triangleCount; ++j) {
  68326. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  68327. for (var ii = 0; ii < 3; ii++) {
  68328. var ofs = 0;
  68329. var vv = triangle.vertices[ii];
  68330. while (ofs < vCount.length) {
  68331. if (vId[ofs] === vv.id)
  68332. break;
  68333. ++ofs;
  68334. }
  68335. if (ofs === vCount.length) {
  68336. vCount.push(1);
  68337. vId.push(vv.id);
  68338. }
  68339. else {
  68340. vCount[ofs]++;
  68341. }
  68342. }
  68343. }
  68344. for (j = 0; j < vCount.length; ++j) {
  68345. if (vCount[j] === 1) {
  68346. this.vertices[vId[j]].isBorder = true;
  68347. }
  68348. else {
  68349. this.vertices[vId[j]].isBorder = false;
  68350. }
  68351. }
  68352. }
  68353. };
  68354. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  68355. if (identifyBorders === void 0) { identifyBorders = false; }
  68356. var i;
  68357. if (!identifyBorders) {
  68358. var newTrianglesVector = [];
  68359. for (i = 0; i < this.triangles.length; ++i) {
  68360. if (!this.triangles[i].deleted) {
  68361. newTrianglesVector.push(this.triangles[i]);
  68362. }
  68363. }
  68364. this.triangles = newTrianglesVector;
  68365. }
  68366. for (i = 0; i < this.vertices.length; ++i) {
  68367. this.vertices[i].triangleCount = 0;
  68368. this.vertices[i].triangleStart = 0;
  68369. }
  68370. var t;
  68371. var j;
  68372. var v;
  68373. for (i = 0; i < this.triangles.length; ++i) {
  68374. t = this.triangles[i];
  68375. for (j = 0; j < 3; ++j) {
  68376. v = t.vertices[j];
  68377. v.triangleCount++;
  68378. }
  68379. }
  68380. var tStart = 0;
  68381. for (i = 0; i < this.vertices.length; ++i) {
  68382. this.vertices[i].triangleStart = tStart;
  68383. tStart += this.vertices[i].triangleCount;
  68384. this.vertices[i].triangleCount = 0;
  68385. }
  68386. var newReferences = new Array(this.triangles.length * 3);
  68387. for (i = 0; i < this.triangles.length; ++i) {
  68388. t = this.triangles[i];
  68389. for (j = 0; j < 3; ++j) {
  68390. v = t.vertices[j];
  68391. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  68392. v.triangleCount++;
  68393. }
  68394. }
  68395. this.references = newReferences;
  68396. if (identifyBorders) {
  68397. this.identifyBorder();
  68398. }
  68399. };
  68400. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  68401. var x = point.x;
  68402. var y = point.y;
  68403. var z = point.z;
  68404. 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
  68405. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  68406. };
  68407. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  68408. var q = vertex1.q.add(vertex2.q);
  68409. var border = vertex1.isBorder && vertex2.isBorder;
  68410. var error = 0;
  68411. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  68412. if (qDet !== 0 && !border) {
  68413. if (!pointResult) {
  68414. pointResult = BABYLON.Vector3.Zero();
  68415. }
  68416. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  68417. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  68418. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  68419. error = this.vertexError(q, pointResult);
  68420. }
  68421. else {
  68422. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  68423. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  68424. var error1 = this.vertexError(q, vertex1.position);
  68425. var error2 = this.vertexError(q, vertex2.position);
  68426. var error3 = this.vertexError(q, p3);
  68427. error = Math.min(error1, error2, error3);
  68428. if (error === error1) {
  68429. if (pointResult) {
  68430. pointResult.copyFrom(vertex1.position);
  68431. }
  68432. }
  68433. else if (error === error2) {
  68434. if (pointResult) {
  68435. pointResult.copyFrom(vertex2.position);
  68436. }
  68437. }
  68438. else {
  68439. if (pointResult) {
  68440. pointResult.copyFrom(p3);
  68441. }
  68442. }
  68443. }
  68444. return error;
  68445. };
  68446. return QuadraticErrorSimplification;
  68447. }());
  68448. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  68449. })(BABYLON || (BABYLON = {}));
  68450. //# sourceMappingURL=babylon.meshSimplification.js.map
  68451. var BABYLON;
  68452. (function (BABYLON) {
  68453. var Internals;
  68454. (function (Internals) {
  68455. var MeshLODLevel = (function () {
  68456. function MeshLODLevel(distance, mesh) {
  68457. this.distance = distance;
  68458. this.mesh = mesh;
  68459. }
  68460. return MeshLODLevel;
  68461. }());
  68462. Internals.MeshLODLevel = MeshLODLevel;
  68463. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68464. })(BABYLON || (BABYLON = {}));
  68465. //# sourceMappingURL=babylon.meshLODLevel.js.map
  68466. var BABYLON;
  68467. (function (BABYLON) {
  68468. // Standard optimizations
  68469. var SceneOptimization = (function () {
  68470. function SceneOptimization(priority) {
  68471. if (priority === void 0) { priority = 0; }
  68472. this.priority = priority;
  68473. this.apply = function (scene) {
  68474. return true; // Return true if everything that can be done was applied
  68475. };
  68476. }
  68477. return SceneOptimization;
  68478. }());
  68479. BABYLON.SceneOptimization = SceneOptimization;
  68480. var TextureOptimization = (function (_super) {
  68481. __extends(TextureOptimization, _super);
  68482. function TextureOptimization(priority, maximumSize) {
  68483. if (priority === void 0) { priority = 0; }
  68484. if (maximumSize === void 0) { maximumSize = 1024; }
  68485. var _this = _super.call(this, priority) || this;
  68486. _this.priority = priority;
  68487. _this.maximumSize = maximumSize;
  68488. _this.apply = function (scene) {
  68489. var allDone = true;
  68490. for (var index = 0; index < scene.textures.length; index++) {
  68491. var texture = scene.textures[index];
  68492. if (!texture.canRescale || texture.getContext) {
  68493. continue;
  68494. }
  68495. var currentSize = texture.getSize();
  68496. var maxDimension = Math.max(currentSize.width, currentSize.height);
  68497. if (maxDimension > _this.maximumSize) {
  68498. texture.scale(0.5);
  68499. allDone = false;
  68500. }
  68501. }
  68502. return allDone;
  68503. };
  68504. return _this;
  68505. }
  68506. return TextureOptimization;
  68507. }(SceneOptimization));
  68508. BABYLON.TextureOptimization = TextureOptimization;
  68509. var HardwareScalingOptimization = (function (_super) {
  68510. __extends(HardwareScalingOptimization, _super);
  68511. function HardwareScalingOptimization(priority, maximumScale) {
  68512. if (priority === void 0) { priority = 0; }
  68513. if (maximumScale === void 0) { maximumScale = 2; }
  68514. var _this = _super.call(this, priority) || this;
  68515. _this.priority = priority;
  68516. _this.maximumScale = maximumScale;
  68517. _this._currentScale = 1;
  68518. _this.apply = function (scene) {
  68519. _this._currentScale++;
  68520. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  68521. return _this._currentScale >= _this.maximumScale;
  68522. };
  68523. return _this;
  68524. }
  68525. return HardwareScalingOptimization;
  68526. }(SceneOptimization));
  68527. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  68528. var ShadowsOptimization = (function (_super) {
  68529. __extends(ShadowsOptimization, _super);
  68530. function ShadowsOptimization() {
  68531. var _this = _super !== null && _super.apply(this, arguments) || this;
  68532. _this.apply = function (scene) {
  68533. scene.shadowsEnabled = false;
  68534. return true;
  68535. };
  68536. return _this;
  68537. }
  68538. return ShadowsOptimization;
  68539. }(SceneOptimization));
  68540. BABYLON.ShadowsOptimization = ShadowsOptimization;
  68541. var PostProcessesOptimization = (function (_super) {
  68542. __extends(PostProcessesOptimization, _super);
  68543. function PostProcessesOptimization() {
  68544. var _this = _super !== null && _super.apply(this, arguments) || this;
  68545. _this.apply = function (scene) {
  68546. scene.postProcessesEnabled = false;
  68547. return true;
  68548. };
  68549. return _this;
  68550. }
  68551. return PostProcessesOptimization;
  68552. }(SceneOptimization));
  68553. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  68554. var LensFlaresOptimization = (function (_super) {
  68555. __extends(LensFlaresOptimization, _super);
  68556. function LensFlaresOptimization() {
  68557. var _this = _super !== null && _super.apply(this, arguments) || this;
  68558. _this.apply = function (scene) {
  68559. scene.lensFlaresEnabled = false;
  68560. return true;
  68561. };
  68562. return _this;
  68563. }
  68564. return LensFlaresOptimization;
  68565. }(SceneOptimization));
  68566. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  68567. var ParticlesOptimization = (function (_super) {
  68568. __extends(ParticlesOptimization, _super);
  68569. function ParticlesOptimization() {
  68570. var _this = _super !== null && _super.apply(this, arguments) || this;
  68571. _this.apply = function (scene) {
  68572. scene.particlesEnabled = false;
  68573. return true;
  68574. };
  68575. return _this;
  68576. }
  68577. return ParticlesOptimization;
  68578. }(SceneOptimization));
  68579. BABYLON.ParticlesOptimization = ParticlesOptimization;
  68580. var RenderTargetsOptimization = (function (_super) {
  68581. __extends(RenderTargetsOptimization, _super);
  68582. function RenderTargetsOptimization() {
  68583. var _this = _super !== null && _super.apply(this, arguments) || this;
  68584. _this.apply = function (scene) {
  68585. scene.renderTargetsEnabled = false;
  68586. return true;
  68587. };
  68588. return _this;
  68589. }
  68590. return RenderTargetsOptimization;
  68591. }(SceneOptimization));
  68592. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  68593. var MergeMeshesOptimization = (function (_super) {
  68594. __extends(MergeMeshesOptimization, _super);
  68595. function MergeMeshesOptimization() {
  68596. var _this = _super !== null && _super.apply(this, arguments) || this;
  68597. _this._canBeMerged = function (abstractMesh) {
  68598. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  68599. return false;
  68600. }
  68601. var mesh = abstractMesh;
  68602. if (!mesh.isVisible || !mesh.isEnabled()) {
  68603. return false;
  68604. }
  68605. if (mesh.instances.length > 0) {
  68606. return false;
  68607. }
  68608. if (mesh.skeleton || mesh.hasLODLevels) {
  68609. return false;
  68610. }
  68611. if (mesh.parent) {
  68612. return false;
  68613. }
  68614. return true;
  68615. };
  68616. _this.apply = function (scene, updateSelectionTree) {
  68617. var globalPool = scene.meshes.slice(0);
  68618. var globalLength = globalPool.length;
  68619. for (var index = 0; index < globalLength; index++) {
  68620. var currentPool = new Array();
  68621. var current = globalPool[index];
  68622. // Checks
  68623. if (!_this._canBeMerged(current)) {
  68624. continue;
  68625. }
  68626. currentPool.push(current);
  68627. // Find compatible meshes
  68628. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  68629. var otherMesh = globalPool[subIndex];
  68630. if (!_this._canBeMerged(otherMesh)) {
  68631. continue;
  68632. }
  68633. if (otherMesh.material !== current.material) {
  68634. continue;
  68635. }
  68636. if (otherMesh.checkCollisions !== current.checkCollisions) {
  68637. continue;
  68638. }
  68639. currentPool.push(otherMesh);
  68640. globalLength--;
  68641. globalPool.splice(subIndex, 1);
  68642. subIndex--;
  68643. }
  68644. if (currentPool.length < 2) {
  68645. continue;
  68646. }
  68647. // Merge meshes
  68648. BABYLON.Mesh.MergeMeshes(currentPool);
  68649. }
  68650. if (updateSelectionTree != undefined) {
  68651. if (updateSelectionTree) {
  68652. scene.createOrUpdateSelectionOctree();
  68653. }
  68654. }
  68655. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  68656. scene.createOrUpdateSelectionOctree();
  68657. }
  68658. return true;
  68659. };
  68660. return _this;
  68661. }
  68662. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  68663. get: function () {
  68664. return MergeMeshesOptimization._UpdateSelectionTree;
  68665. },
  68666. set: function (value) {
  68667. MergeMeshesOptimization._UpdateSelectionTree = value;
  68668. },
  68669. enumerable: true,
  68670. configurable: true
  68671. });
  68672. return MergeMeshesOptimization;
  68673. }(SceneOptimization));
  68674. MergeMeshesOptimization._UpdateSelectionTree = false;
  68675. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  68676. // Options
  68677. var SceneOptimizerOptions = (function () {
  68678. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  68679. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  68680. if (trackerDuration === void 0) { trackerDuration = 2000; }
  68681. this.targetFrameRate = targetFrameRate;
  68682. this.trackerDuration = trackerDuration;
  68683. this.optimizations = new Array();
  68684. }
  68685. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  68686. var result = new SceneOptimizerOptions(targetFrameRate);
  68687. var priority = 0;
  68688. result.optimizations.push(new MergeMeshesOptimization(priority));
  68689. result.optimizations.push(new ShadowsOptimization(priority));
  68690. result.optimizations.push(new LensFlaresOptimization(priority));
  68691. // Next priority
  68692. priority++;
  68693. result.optimizations.push(new PostProcessesOptimization(priority));
  68694. result.optimizations.push(new ParticlesOptimization(priority));
  68695. // Next priority
  68696. priority++;
  68697. result.optimizations.push(new TextureOptimization(priority, 1024));
  68698. return result;
  68699. };
  68700. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  68701. var result = new SceneOptimizerOptions(targetFrameRate);
  68702. var priority = 0;
  68703. result.optimizations.push(new MergeMeshesOptimization(priority));
  68704. result.optimizations.push(new ShadowsOptimization(priority));
  68705. result.optimizations.push(new LensFlaresOptimization(priority));
  68706. // Next priority
  68707. priority++;
  68708. result.optimizations.push(new PostProcessesOptimization(priority));
  68709. result.optimizations.push(new ParticlesOptimization(priority));
  68710. // Next priority
  68711. priority++;
  68712. result.optimizations.push(new TextureOptimization(priority, 512));
  68713. // Next priority
  68714. priority++;
  68715. result.optimizations.push(new RenderTargetsOptimization(priority));
  68716. // Next priority
  68717. priority++;
  68718. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  68719. return result;
  68720. };
  68721. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  68722. var result = new SceneOptimizerOptions(targetFrameRate);
  68723. var priority = 0;
  68724. result.optimizations.push(new MergeMeshesOptimization(priority));
  68725. result.optimizations.push(new ShadowsOptimization(priority));
  68726. result.optimizations.push(new LensFlaresOptimization(priority));
  68727. // Next priority
  68728. priority++;
  68729. result.optimizations.push(new PostProcessesOptimization(priority));
  68730. result.optimizations.push(new ParticlesOptimization(priority));
  68731. // Next priority
  68732. priority++;
  68733. result.optimizations.push(new TextureOptimization(priority, 256));
  68734. // Next priority
  68735. priority++;
  68736. result.optimizations.push(new RenderTargetsOptimization(priority));
  68737. // Next priority
  68738. priority++;
  68739. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  68740. return result;
  68741. };
  68742. return SceneOptimizerOptions;
  68743. }());
  68744. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  68745. // Scene optimizer tool
  68746. var SceneOptimizer = (function () {
  68747. function SceneOptimizer() {
  68748. }
  68749. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  68750. // TODO: add an epsilon
  68751. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  68752. if (onSuccess) {
  68753. onSuccess();
  68754. }
  68755. return;
  68756. }
  68757. // Apply current level of optimizations
  68758. var allDone = true;
  68759. var noOptimizationApplied = true;
  68760. for (var index = 0; index < options.optimizations.length; index++) {
  68761. var optimization = options.optimizations[index];
  68762. if (optimization.priority === currentPriorityLevel) {
  68763. noOptimizationApplied = false;
  68764. allDone = allDone && optimization.apply(scene);
  68765. }
  68766. }
  68767. // If no optimization was applied, this is a failure :(
  68768. if (noOptimizationApplied) {
  68769. if (onFailure) {
  68770. onFailure();
  68771. }
  68772. return;
  68773. }
  68774. // If all optimizations were done, move to next level
  68775. if (allDone) {
  68776. currentPriorityLevel++;
  68777. }
  68778. // Let's the system running for a specific amount of time before checking FPS
  68779. scene.executeWhenReady(function () {
  68780. setTimeout(function () {
  68781. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  68782. }, options.trackerDuration);
  68783. });
  68784. };
  68785. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  68786. if (!options) {
  68787. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  68788. }
  68789. // Let's the system running for a specific amount of time before checking FPS
  68790. scene.executeWhenReady(function () {
  68791. setTimeout(function () {
  68792. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  68793. }, options.trackerDuration);
  68794. });
  68795. };
  68796. return SceneOptimizer;
  68797. }());
  68798. BABYLON.SceneOptimizer = SceneOptimizer;
  68799. })(BABYLON || (BABYLON = {}));
  68800. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  68801. var BABYLON;
  68802. (function (BABYLON) {
  68803. var OutlineRenderer = (function () {
  68804. function OutlineRenderer(scene) {
  68805. this.zOffset = 1;
  68806. this._scene = scene;
  68807. }
  68808. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  68809. var _this = this;
  68810. if (useOverlay === void 0) { useOverlay = false; }
  68811. var scene = this._scene;
  68812. var engine = this._scene.getEngine();
  68813. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68814. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  68815. return;
  68816. }
  68817. var mesh = subMesh.getRenderingMesh();
  68818. var material = subMesh.getMaterial();
  68819. engine.enableEffect(this._effect);
  68820. // Logarithmic depth
  68821. if (material.useLogarithmicDepth) {
  68822. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  68823. }
  68824. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  68825. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  68826. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68827. // Bones
  68828. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68829. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68830. }
  68831. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  68832. // Alpha test
  68833. if (material && material.needAlphaTesting()) {
  68834. var alphaTexture = material.getAlphaTestTexture();
  68835. if (alphaTexture) {
  68836. this._effect.setTexture("diffuseSampler", alphaTexture);
  68837. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68838. }
  68839. }
  68840. engine.setZOffset(-this.zOffset);
  68841. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  68842. engine.setZOffset(0);
  68843. };
  68844. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  68845. var defines = [];
  68846. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68847. var mesh = subMesh.getMesh();
  68848. var material = subMesh.getMaterial();
  68849. if (material) {
  68850. // Alpha test
  68851. if (material.needAlphaTesting()) {
  68852. defines.push("#define ALPHATEST");
  68853. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68854. attribs.push(BABYLON.VertexBuffer.UVKind);
  68855. defines.push("#define UV1");
  68856. }
  68857. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68858. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68859. defines.push("#define UV2");
  68860. }
  68861. }
  68862. //Logarithmic depth
  68863. if (material.useLogarithmicDepth) {
  68864. defines.push("#define LOGARITHMICDEPTH");
  68865. }
  68866. }
  68867. // Bones
  68868. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68869. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68870. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68871. if (mesh.numBoneInfluencers > 4) {
  68872. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68873. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68874. }
  68875. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68876. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68877. }
  68878. else {
  68879. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68880. }
  68881. // Instances
  68882. if (useInstances) {
  68883. defines.push("#define INSTANCES");
  68884. attribs.push("world0");
  68885. attribs.push("world1");
  68886. attribs.push("world2");
  68887. attribs.push("world3");
  68888. }
  68889. // Get correct effect
  68890. var join = defines.join("\n");
  68891. if (this._cachedDefines !== join) {
  68892. this._cachedDefines = join;
  68893. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  68894. }
  68895. return this._effect.isReady();
  68896. };
  68897. return OutlineRenderer;
  68898. }());
  68899. BABYLON.OutlineRenderer = OutlineRenderer;
  68900. })(BABYLON || (BABYLON = {}));
  68901. //# sourceMappingURL=babylon.outlineRenderer.js.map
  68902. var BABYLON;
  68903. (function (BABYLON) {
  68904. var FaceAdjacencies = (function () {
  68905. function FaceAdjacencies() {
  68906. this.edges = new Array();
  68907. this.edgesConnectedCount = 0;
  68908. }
  68909. return FaceAdjacencies;
  68910. }());
  68911. var EdgesRenderer = (function () {
  68912. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  68913. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  68914. if (epsilon === void 0) { epsilon = 0.95; }
  68915. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  68916. this.edgesWidthScalerForOrthographic = 1000.0;
  68917. this.edgesWidthScalerForPerspective = 50.0;
  68918. this._linesPositions = new Array();
  68919. this._linesNormals = new Array();
  68920. this._linesIndices = new Array();
  68921. this._buffers = {};
  68922. this._checkVerticesInsteadOfIndices = false;
  68923. this._source = source;
  68924. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  68925. this._epsilon = epsilon;
  68926. this._prepareRessources();
  68927. this._generateEdgesLines();
  68928. }
  68929. EdgesRenderer.prototype._prepareRessources = function () {
  68930. if (this._lineShader) {
  68931. return;
  68932. }
  68933. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  68934. attributes: ["position", "normal"],
  68935. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  68936. });
  68937. this._lineShader.disableDepthWrite = true;
  68938. this._lineShader.backFaceCulling = false;
  68939. };
  68940. EdgesRenderer.prototype._rebuild = function () {
  68941. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  68942. if (buffer) {
  68943. buffer._rebuild();
  68944. }
  68945. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  68946. if (buffer) {
  68947. buffer._rebuild();
  68948. }
  68949. var scene = this._source.getScene();
  68950. var engine = scene.getEngine();
  68951. this._ib = engine.createIndexBuffer(this._linesIndices);
  68952. };
  68953. EdgesRenderer.prototype.dispose = function () {
  68954. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  68955. if (buffer) {
  68956. buffer.dispose();
  68957. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  68958. }
  68959. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  68960. if (buffer) {
  68961. buffer.dispose();
  68962. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  68963. }
  68964. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  68965. this._lineShader.dispose();
  68966. };
  68967. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  68968. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  68969. return 0;
  68970. }
  68971. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  68972. return 1;
  68973. }
  68974. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  68975. return 2;
  68976. }
  68977. return -1;
  68978. };
  68979. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  68980. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  68981. return 0;
  68982. }
  68983. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  68984. return 1;
  68985. }
  68986. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  68987. return 2;
  68988. }
  68989. return -1;
  68990. };
  68991. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  68992. var needToCreateLine;
  68993. if (edge === undefined) {
  68994. needToCreateLine = true;
  68995. }
  68996. else {
  68997. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  68998. needToCreateLine = dotProduct < this._epsilon;
  68999. }
  69000. if (needToCreateLine) {
  69001. var offset = this._linesPositions.length / 3;
  69002. var normal = p0.subtract(p1);
  69003. normal.normalize();
  69004. // Positions
  69005. this._linesPositions.push(p0.x);
  69006. this._linesPositions.push(p0.y);
  69007. this._linesPositions.push(p0.z);
  69008. this._linesPositions.push(p0.x);
  69009. this._linesPositions.push(p0.y);
  69010. this._linesPositions.push(p0.z);
  69011. this._linesPositions.push(p1.x);
  69012. this._linesPositions.push(p1.y);
  69013. this._linesPositions.push(p1.z);
  69014. this._linesPositions.push(p1.x);
  69015. this._linesPositions.push(p1.y);
  69016. this._linesPositions.push(p1.z);
  69017. // Normals
  69018. this._linesNormals.push(p1.x);
  69019. this._linesNormals.push(p1.y);
  69020. this._linesNormals.push(p1.z);
  69021. this._linesNormals.push(-1);
  69022. this._linesNormals.push(p1.x);
  69023. this._linesNormals.push(p1.y);
  69024. this._linesNormals.push(p1.z);
  69025. this._linesNormals.push(1);
  69026. this._linesNormals.push(p0.x);
  69027. this._linesNormals.push(p0.y);
  69028. this._linesNormals.push(p0.z);
  69029. this._linesNormals.push(-1);
  69030. this._linesNormals.push(p0.x);
  69031. this._linesNormals.push(p0.y);
  69032. this._linesNormals.push(p0.z);
  69033. this._linesNormals.push(1);
  69034. // Indices
  69035. this._linesIndices.push(offset);
  69036. this._linesIndices.push(offset + 1);
  69037. this._linesIndices.push(offset + 2);
  69038. this._linesIndices.push(offset);
  69039. this._linesIndices.push(offset + 2);
  69040. this._linesIndices.push(offset + 3);
  69041. }
  69042. };
  69043. EdgesRenderer.prototype._generateEdgesLines = function () {
  69044. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69045. var indices = this._source.getIndices();
  69046. // First let's find adjacencies
  69047. var adjacencies = new Array();
  69048. var faceNormals = new Array();
  69049. var index;
  69050. var faceAdjacencies;
  69051. // Prepare faces
  69052. for (index = 0; index < indices.length; index += 3) {
  69053. faceAdjacencies = new FaceAdjacencies();
  69054. var p0Index = indices[index];
  69055. var p1Index = indices[index + 1];
  69056. var p2Index = indices[index + 2];
  69057. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  69058. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  69059. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  69060. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  69061. faceNormal.normalize();
  69062. faceNormals.push(faceNormal);
  69063. adjacencies.push(faceAdjacencies);
  69064. }
  69065. // Scan
  69066. for (index = 0; index < adjacencies.length; index++) {
  69067. faceAdjacencies = adjacencies[index];
  69068. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  69069. var otherFaceAdjacencies = adjacencies[otherIndex];
  69070. if (faceAdjacencies.edgesConnectedCount === 3) {
  69071. break;
  69072. }
  69073. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  69074. continue;
  69075. }
  69076. var otherP0 = indices[otherIndex * 3];
  69077. var otherP1 = indices[otherIndex * 3 + 1];
  69078. var otherP2 = indices[otherIndex * 3 + 2];
  69079. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  69080. var otherEdgeIndex;
  69081. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  69082. continue;
  69083. }
  69084. switch (edgeIndex) {
  69085. case 0:
  69086. if (this._checkVerticesInsteadOfIndices) {
  69087. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  69088. }
  69089. else {
  69090. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  69091. }
  69092. break;
  69093. case 1:
  69094. if (this._checkVerticesInsteadOfIndices) {
  69095. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  69096. }
  69097. else {
  69098. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  69099. }
  69100. break;
  69101. case 2:
  69102. if (this._checkVerticesInsteadOfIndices) {
  69103. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  69104. }
  69105. else {
  69106. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  69107. }
  69108. break;
  69109. }
  69110. if (otherEdgeIndex === -1) {
  69111. continue;
  69112. }
  69113. faceAdjacencies.edges[edgeIndex] = otherIndex;
  69114. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  69115. faceAdjacencies.edgesConnectedCount++;
  69116. otherFaceAdjacencies.edgesConnectedCount++;
  69117. if (faceAdjacencies.edgesConnectedCount === 3) {
  69118. break;
  69119. }
  69120. }
  69121. }
  69122. }
  69123. // Create lines
  69124. for (index = 0; index < adjacencies.length; index++) {
  69125. // 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
  69126. var current = adjacencies[index];
  69127. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  69128. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  69129. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  69130. }
  69131. // Merge into a single mesh
  69132. var engine = this._source.getScene().getEngine();
  69133. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  69134. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  69135. this._ib = engine.createIndexBuffer(this._linesIndices);
  69136. this._indicesCount = this._linesIndices.length;
  69137. };
  69138. EdgesRenderer.prototype.render = function () {
  69139. if (!this._lineShader.isReady()) {
  69140. return;
  69141. }
  69142. var scene = this._source.getScene();
  69143. var engine = scene.getEngine();
  69144. this._lineShader._preBind();
  69145. // VBOs
  69146. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  69147. scene.resetCachedMaterial();
  69148. this._lineShader.setColor4("color", this._source.edgesColor);
  69149. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  69150. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  69151. }
  69152. else {
  69153. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  69154. }
  69155. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  69156. this._lineShader.bind(this._source.getWorldMatrix());
  69157. // Draw order
  69158. engine.draw(true, 0, this._indicesCount);
  69159. this._lineShader.unbind();
  69160. engine.setDepthWrite(true);
  69161. };
  69162. return EdgesRenderer;
  69163. }());
  69164. BABYLON.EdgesRenderer = EdgesRenderer;
  69165. })(BABYLON || (BABYLON = {}));
  69166. //# sourceMappingURL=babylon.edgesRenderer.js.map
  69167. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  69168. /// <reference path="..\Math\babylon.math.ts" />
  69169. var BABYLON;
  69170. (function (BABYLON) {
  69171. /**
  69172. * Special Glow Blur post process only blurring the alpha channel
  69173. * It enforces keeping the most luminous color in the color channel.
  69174. */
  69175. var GlowBlurPostProcess = (function (_super) {
  69176. __extends(GlowBlurPostProcess, _super);
  69177. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  69178. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69179. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  69180. _this.direction = direction;
  69181. _this.kernel = kernel;
  69182. _this.onApplyObservable.add(function (effect) {
  69183. effect.setFloat2("screenSize", _this.width, _this.height);
  69184. effect.setVector2("direction", _this.direction);
  69185. effect.setFloat("blurWidth", _this.kernel);
  69186. });
  69187. return _this;
  69188. }
  69189. return GlowBlurPostProcess;
  69190. }(BABYLON.PostProcess));
  69191. /**
  69192. * The highlight layer Helps adding a glow effect around a mesh.
  69193. *
  69194. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  69195. * glowy meshes to your scene.
  69196. *
  69197. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  69198. */
  69199. var HighlightLayer = (function () {
  69200. /**
  69201. * Instantiates a new highlight Layer and references it to the scene..
  69202. * @param name The name of the layer
  69203. * @param scene The scene to use the layer in
  69204. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  69205. */
  69206. function HighlightLayer(name, scene, options) {
  69207. this.name = name;
  69208. this._vertexBuffers = {};
  69209. this._mainTextureDesiredSize = { width: 0, height: 0 };
  69210. this._meshes = {};
  69211. this._maxSize = 0;
  69212. this._shouldRender = false;
  69213. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  69214. this._excludedMeshes = {};
  69215. /**
  69216. * Specifies whether or not the inner glow is ACTIVE in the layer.
  69217. */
  69218. this.innerGlow = true;
  69219. /**
  69220. * Specifies whether or not the outer glow is ACTIVE in the layer.
  69221. */
  69222. this.outerGlow = true;
  69223. /**
  69224. * Specifies wether the highlight layer is enabled or not.
  69225. */
  69226. this.isEnabled = true;
  69227. /**
  69228. * An event triggered when the highlight layer has been disposed.
  69229. * @type {BABYLON.Observable}
  69230. */
  69231. this.onDisposeObservable = new BABYLON.Observable();
  69232. /**
  69233. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  69234. * @type {BABYLON.Observable}
  69235. */
  69236. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  69237. /**
  69238. * An event triggered when the highlight layer is being blurred.
  69239. * @type {BABYLON.Observable}
  69240. */
  69241. this.onBeforeBlurObservable = new BABYLON.Observable();
  69242. /**
  69243. * An event triggered when the highlight layer has been blurred.
  69244. * @type {BABYLON.Observable}
  69245. */
  69246. this.onAfterBlurObservable = new BABYLON.Observable();
  69247. /**
  69248. * An event triggered when the glowing blurred texture is being merged in the scene.
  69249. * @type {BABYLON.Observable}
  69250. */
  69251. this.onBeforeComposeObservable = new BABYLON.Observable();
  69252. /**
  69253. * An event triggered when the glowing blurred texture has been merged in the scene.
  69254. * @type {BABYLON.Observable}
  69255. */
  69256. this.onAfterComposeObservable = new BABYLON.Observable();
  69257. /**
  69258. * An event triggered when the highlight layer changes its size.
  69259. * @type {BABYLON.Observable}
  69260. */
  69261. this.onSizeChangedObservable = new BABYLON.Observable();
  69262. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69263. var engine = scene.getEngine();
  69264. this._engine = engine;
  69265. this._maxSize = this._engine.getCaps().maxTextureSize;
  69266. this._scene.highlightLayers.push(this);
  69267. // Warn on stencil.
  69268. if (!this._engine.isStencilEnable) {
  69269. 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 }");
  69270. }
  69271. // Adapt options
  69272. this._options = options || {
  69273. mainTextureRatio: 0.5,
  69274. blurTextureSizeRatio: 0.5,
  69275. blurHorizontalSize: 1.0,
  69276. blurVerticalSize: 1.0,
  69277. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  69278. };
  69279. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  69280. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  69281. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  69282. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  69283. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  69284. // VBO
  69285. var vertices = [];
  69286. vertices.push(1, 1);
  69287. vertices.push(-1, 1);
  69288. vertices.push(-1, -1);
  69289. vertices.push(1, -1);
  69290. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69291. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  69292. this._createIndexBuffer();
  69293. // Effect
  69294. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  69295. // Render target
  69296. this.setMainTextureSize();
  69297. // Create Textures and post processes
  69298. this.createTextureAndPostProcesses();
  69299. }
  69300. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  69301. /**
  69302. * Gets the horizontal size of the blur.
  69303. */
  69304. get: function () {
  69305. return this._horizontalBlurPostprocess.kernel;
  69306. },
  69307. /**
  69308. * Specifies the horizontal size of the blur.
  69309. */
  69310. set: function (value) {
  69311. this._horizontalBlurPostprocess.kernel = value;
  69312. },
  69313. enumerable: true,
  69314. configurable: true
  69315. });
  69316. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  69317. /**
  69318. * Gets the vertical size of the blur.
  69319. */
  69320. get: function () {
  69321. return this._verticalBlurPostprocess.kernel;
  69322. },
  69323. /**
  69324. * Specifies the vertical size of the blur.
  69325. */
  69326. set: function (value) {
  69327. this._verticalBlurPostprocess.kernel = value;
  69328. },
  69329. enumerable: true,
  69330. configurable: true
  69331. });
  69332. Object.defineProperty(HighlightLayer.prototype, "camera", {
  69333. /**
  69334. * Gets the camera attached to the layer.
  69335. */
  69336. get: function () {
  69337. return this._options.camera;
  69338. },
  69339. enumerable: true,
  69340. configurable: true
  69341. });
  69342. HighlightLayer.prototype._createIndexBuffer = function () {
  69343. var engine = this._scene.getEngine();
  69344. // Indices
  69345. var indices = [];
  69346. indices.push(0);
  69347. indices.push(1);
  69348. indices.push(2);
  69349. indices.push(0);
  69350. indices.push(2);
  69351. indices.push(3);
  69352. this._indexBuffer = engine.createIndexBuffer(indices);
  69353. };
  69354. HighlightLayer.prototype._rebuild = function () {
  69355. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  69356. this._createIndexBuffer();
  69357. };
  69358. /**
  69359. * Creates the render target textures and post processes used in the highlight layer.
  69360. */
  69361. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  69362. var _this = this;
  69363. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  69364. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  69365. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  69366. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  69367. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  69368. width: this._mainTextureDesiredSize.width,
  69369. height: this._mainTextureDesiredSize.height
  69370. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69371. this._mainTexture.activeCamera = this._options.camera;
  69372. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69373. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69374. this._mainTexture.anisotropicFilteringLevel = 1;
  69375. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69376. this._mainTexture.renderParticles = false;
  69377. this._mainTexture.renderList = null;
  69378. this._mainTexture.ignoreCameraViewport = true;
  69379. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  69380. width: blurTextureWidth,
  69381. height: blurTextureHeight
  69382. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69383. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69384. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69385. this._blurTexture.anisotropicFilteringLevel = 16;
  69386. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69387. this._blurTexture.renderParticles = false;
  69388. this._blurTexture.ignoreCameraViewport = true;
  69389. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69390. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  69391. effect.setTexture("textureSampler", _this._mainTexture);
  69392. });
  69393. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  69394. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69395. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  69396. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69397. });
  69398. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69399. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  69400. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69401. });
  69402. }
  69403. else {
  69404. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69405. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  69406. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69407. });
  69408. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69409. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  69410. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69411. });
  69412. }
  69413. this._mainTexture.onAfterUnbindObservable.add(function () {
  69414. _this.onBeforeBlurObservable.notifyObservers(_this);
  69415. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture(), true);
  69416. _this.onAfterBlurObservable.notifyObservers(_this);
  69417. });
  69418. // Custom render function
  69419. var renderSubMesh = function (subMesh) {
  69420. var mesh = subMesh.getRenderingMesh();
  69421. var scene = _this._scene;
  69422. var engine = scene.getEngine();
  69423. // Culling
  69424. engine.setState(subMesh.getMaterial().backFaceCulling);
  69425. // Managing instances
  69426. var batch = mesh._getInstancesRenderList(subMesh._id);
  69427. if (batch.mustReturn) {
  69428. return;
  69429. }
  69430. // Excluded Mesh
  69431. if (_this._excludedMeshes[mesh.uniqueId]) {
  69432. return;
  69433. }
  69434. ;
  69435. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  69436. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  69437. var material = subMesh.getMaterial();
  69438. var emissiveTexture = null;
  69439. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  69440. emissiveTexture = material.emissiveTexture;
  69441. }
  69442. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  69443. engine.enableEffect(_this._glowMapGenerationEffect);
  69444. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  69445. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  69446. if (highlightLayerMesh) {
  69447. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  69448. }
  69449. else {
  69450. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  69451. }
  69452. // Alpha test
  69453. if (material && material.needAlphaTesting()) {
  69454. var alphaTexture = material.getAlphaTestTexture();
  69455. if (alphaTexture) {
  69456. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  69457. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69458. }
  69459. }
  69460. // Glow emissive only
  69461. if (emissiveTexture) {
  69462. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  69463. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  69464. }
  69465. // Bones
  69466. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69467. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69468. }
  69469. // Draw
  69470. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  69471. }
  69472. else {
  69473. // Need to reset refresh rate of the shadowMap
  69474. _this._mainTexture.resetRefreshCounter();
  69475. }
  69476. };
  69477. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69478. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  69479. var index;
  69480. var engine = _this._scene.getEngine();
  69481. if (depthOnlySubMeshes.length) {
  69482. engine.setColorWrite(false);
  69483. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69484. renderSubMesh(depthOnlySubMeshes.data[index]);
  69485. }
  69486. engine.setColorWrite(true);
  69487. }
  69488. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69489. renderSubMesh(opaqueSubMeshes.data[index]);
  69490. }
  69491. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69492. renderSubMesh(alphaTestSubMeshes.data[index]);
  69493. }
  69494. for (index = 0; index < transparentSubMeshes.length; index++) {
  69495. renderSubMesh(transparentSubMeshes.data[index]);
  69496. }
  69497. };
  69498. this._mainTexture.onClearObservable.add(function (engine) {
  69499. engine.clear(HighlightLayer.neutralColor, true, true, true);
  69500. });
  69501. };
  69502. /**
  69503. * Checks for the readiness of the element composing the layer.
  69504. * @param subMesh the mesh to check for
  69505. * @param useInstances specify wether or not to use instances to render the mesh
  69506. * @param emissiveTexture the associated emissive texture used to generate the glow
  69507. * @return true if ready otherwise, false
  69508. */
  69509. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  69510. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  69511. return false;
  69512. }
  69513. var defines = [];
  69514. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69515. var mesh = subMesh.getMesh();
  69516. var material = subMesh.getMaterial();
  69517. var uv1 = false;
  69518. var uv2 = false;
  69519. // Alpha test
  69520. if (material && material.needAlphaTesting()) {
  69521. var alphaTexture = material.getAlphaTestTexture();
  69522. if (alphaTexture) {
  69523. defines.push("#define ALPHATEST");
  69524. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  69525. alphaTexture.coordinatesIndex === 1) {
  69526. defines.push("#define DIFFUSEUV2");
  69527. uv2 = true;
  69528. }
  69529. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69530. defines.push("#define DIFFUSEUV1");
  69531. uv1 = true;
  69532. }
  69533. }
  69534. }
  69535. // Emissive
  69536. if (emissiveTexture) {
  69537. defines.push("#define EMISSIVE");
  69538. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  69539. emissiveTexture.coordinatesIndex === 1) {
  69540. defines.push("#define EMISSIVEUV2");
  69541. uv2 = true;
  69542. }
  69543. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69544. defines.push("#define EMISSIVEUV1");
  69545. uv1 = true;
  69546. }
  69547. }
  69548. if (uv1) {
  69549. attribs.push(BABYLON.VertexBuffer.UVKind);
  69550. defines.push("#define UV1");
  69551. }
  69552. if (uv2) {
  69553. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69554. defines.push("#define UV2");
  69555. }
  69556. // Bones
  69557. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69558. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69559. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69560. if (mesh.numBoneInfluencers > 4) {
  69561. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69562. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69563. }
  69564. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69565. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  69566. }
  69567. else {
  69568. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69569. }
  69570. // Instances
  69571. if (useInstances) {
  69572. defines.push("#define INSTANCES");
  69573. attribs.push("world0");
  69574. attribs.push("world1");
  69575. attribs.push("world2");
  69576. attribs.push("world3");
  69577. }
  69578. // Get correct effect
  69579. var join = defines.join("\n");
  69580. if (this._cachedDefines !== join) {
  69581. this._cachedDefines = join;
  69582. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  69583. }
  69584. return this._glowMapGenerationEffect.isReady();
  69585. };
  69586. /**
  69587. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  69588. */
  69589. HighlightLayer.prototype.render = function () {
  69590. var currentEffect = this._glowMapMergeEffect;
  69591. // Check
  69592. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  69593. return;
  69594. var engine = this._scene.getEngine();
  69595. this.onBeforeComposeObservable.notifyObservers(this);
  69596. // Render
  69597. engine.enableEffect(currentEffect);
  69598. engine.setState(false);
  69599. // Cache
  69600. var previousStencilBuffer = engine.getStencilBuffer();
  69601. var previousStencilFunction = engine.getStencilFunction();
  69602. var previousStencilMask = engine.getStencilMask();
  69603. var previousStencilOperationPass = engine.getStencilOperationPass();
  69604. var previousStencilOperationFail = engine.getStencilOperationFail();
  69605. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  69606. var previousAlphaMode = engine.getAlphaMode();
  69607. // Texture
  69608. currentEffect.setTexture("textureSampler", this._blurTexture);
  69609. // VBOs
  69610. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  69611. // Stencil operations
  69612. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  69613. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  69614. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  69615. // Draw order
  69616. engine.setAlphaMode(this._options.alphaBlendingMode);
  69617. engine.setStencilMask(0x00);
  69618. engine.setStencilBuffer(true);
  69619. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  69620. if (this.outerGlow) {
  69621. currentEffect.setFloat("offset", 0);
  69622. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  69623. engine.draw(true, 0, 6);
  69624. }
  69625. if (this.innerGlow) {
  69626. currentEffect.setFloat("offset", 1);
  69627. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  69628. engine.draw(true, 0, 6);
  69629. }
  69630. // Restore Cache
  69631. engine.setStencilFunction(previousStencilFunction);
  69632. engine.setStencilMask(previousStencilMask);
  69633. engine.setAlphaMode(previousAlphaMode);
  69634. engine.setStencilBuffer(previousStencilBuffer);
  69635. engine.setStencilOperationPass(previousStencilOperationPass);
  69636. engine.setStencilOperationFail(previousStencilOperationFail);
  69637. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  69638. engine._stencilState.reset();
  69639. this.onAfterComposeObservable.notifyObservers(this);
  69640. // Handle size changes.
  69641. var size = this._mainTexture.getSize();
  69642. this.setMainTextureSize();
  69643. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  69644. // Recreate RTT and post processes on size change.
  69645. this.onSizeChangedObservable.notifyObservers(this);
  69646. this.disposeTextureAndPostProcesses();
  69647. this.createTextureAndPostProcesses();
  69648. }
  69649. };
  69650. /**
  69651. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  69652. * @param mesh The mesh to exclude from the highlight layer
  69653. */
  69654. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  69655. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  69656. if (!meshExcluded) {
  69657. this._excludedMeshes[mesh.uniqueId] = {
  69658. mesh: mesh,
  69659. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  69660. mesh.getEngine().setStencilBuffer(false);
  69661. }),
  69662. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  69663. mesh.getEngine().setStencilBuffer(true);
  69664. }),
  69665. };
  69666. }
  69667. };
  69668. /**
  69669. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  69670. * @param mesh The mesh to highlight
  69671. */
  69672. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  69673. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  69674. if (meshExcluded) {
  69675. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  69676. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  69677. }
  69678. this._excludedMeshes[mesh.uniqueId] = undefined;
  69679. };
  69680. /**
  69681. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  69682. * @param mesh The mesh to highlight
  69683. * @param color The color of the highlight
  69684. * @param glowEmissiveOnly Extract the glow from the emissive texture
  69685. */
  69686. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  69687. var _this = this;
  69688. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  69689. var meshHighlight = this._meshes[mesh.uniqueId];
  69690. if (meshHighlight) {
  69691. meshHighlight.color = color;
  69692. }
  69693. else {
  69694. this._meshes[mesh.uniqueId] = {
  69695. mesh: mesh,
  69696. color: color,
  69697. // Lambda required for capture due to Observable this context
  69698. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  69699. if (_this._excludedMeshes[mesh.uniqueId]) {
  69700. _this.defaultStencilReference(mesh);
  69701. }
  69702. else {
  69703. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  69704. }
  69705. }),
  69706. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  69707. glowEmissiveOnly: glowEmissiveOnly
  69708. };
  69709. }
  69710. this._shouldRender = true;
  69711. };
  69712. /**
  69713. * Remove a mesh from the highlight layer in order to make it stop glowing.
  69714. * @param mesh The mesh to highlight
  69715. */
  69716. HighlightLayer.prototype.removeMesh = function (mesh) {
  69717. var meshHighlight = this._meshes[mesh.uniqueId];
  69718. if (meshHighlight) {
  69719. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  69720. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  69721. }
  69722. this._meshes[mesh.uniqueId] = undefined;
  69723. this._shouldRender = false;
  69724. for (var meshHighlightToCheck in this._meshes) {
  69725. if (meshHighlightToCheck) {
  69726. this._shouldRender = true;
  69727. break;
  69728. }
  69729. }
  69730. };
  69731. /**
  69732. * Returns true if the layer contains information to display, otherwise false.
  69733. */
  69734. HighlightLayer.prototype.shouldRender = function () {
  69735. return this.isEnabled && this._shouldRender;
  69736. };
  69737. /**
  69738. * Sets the main texture desired size which is the closest power of two
  69739. * of the engine canvas size.
  69740. */
  69741. HighlightLayer.prototype.setMainTextureSize = function () {
  69742. if (this._options.mainTextureFixedSize) {
  69743. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  69744. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  69745. }
  69746. else {
  69747. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  69748. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  69749. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  69750. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  69751. }
  69752. };
  69753. /**
  69754. * Force the stencil to the normal expected value for none glowing parts
  69755. */
  69756. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  69757. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  69758. };
  69759. /**
  69760. * Dispose only the render target textures and post process.
  69761. */
  69762. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  69763. this._blurTexture.dispose();
  69764. this._mainTexture.dispose();
  69765. this._downSamplePostprocess.dispose();
  69766. this._horizontalBlurPostprocess.dispose();
  69767. this._verticalBlurPostprocess.dispose();
  69768. };
  69769. /**
  69770. * Dispose the highlight layer and free resources.
  69771. */
  69772. HighlightLayer.prototype.dispose = function () {
  69773. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69774. if (vertexBuffer) {
  69775. vertexBuffer.dispose();
  69776. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69777. }
  69778. if (this._indexBuffer) {
  69779. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69780. this._indexBuffer = null;
  69781. }
  69782. // Clean textures and post processes
  69783. this.disposeTextureAndPostProcesses();
  69784. // Clean mesh references
  69785. for (var id in this._meshes) {
  69786. var meshHighlight = this._meshes[id];
  69787. if (meshHighlight && meshHighlight.mesh) {
  69788. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  69789. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  69790. }
  69791. }
  69792. this._meshes = null;
  69793. for (var id in this._excludedMeshes) {
  69794. var meshHighlight = this._excludedMeshes[id];
  69795. if (meshHighlight) {
  69796. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  69797. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  69798. }
  69799. }
  69800. this._excludedMeshes = null;
  69801. // Remove from scene
  69802. var index = this._scene.highlightLayers.indexOf(this, 0);
  69803. if (index > -1) {
  69804. this._scene.highlightLayers.splice(index, 1);
  69805. }
  69806. // Callback
  69807. this.onDisposeObservable.notifyObservers(this);
  69808. this.onDisposeObservable.clear();
  69809. this.onBeforeRenderMainTextureObservable.clear();
  69810. this.onBeforeBlurObservable.clear();
  69811. this.onBeforeComposeObservable.clear();
  69812. this.onAfterComposeObservable.clear();
  69813. this.onSizeChangedObservable.clear();
  69814. };
  69815. return HighlightLayer;
  69816. }());
  69817. /**
  69818. * The neutral color used during the preparation of the glow effect.
  69819. * This is black by default as the blend operation is a blend operation.
  69820. */
  69821. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  69822. /**
  69823. * Stencil value used for glowing meshes.
  69824. */
  69825. HighlightLayer.glowingMeshStencilReference = 0x02;
  69826. /**
  69827. * Stencil value used for the other meshes in the scene.
  69828. */
  69829. HighlightLayer.normalMeshStencilReference = 0x01;
  69830. BABYLON.HighlightLayer = HighlightLayer;
  69831. })(BABYLON || (BABYLON = {}));
  69832. //# sourceMappingURL=babylon.highlightlayer.js.map
  69833. var BABYLON;
  69834. (function (BABYLON) {
  69835. var MeshAssetTask = (function () {
  69836. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  69837. this.name = name;
  69838. this.meshesNames = meshesNames;
  69839. this.rootUrl = rootUrl;
  69840. this.sceneFilename = sceneFilename;
  69841. this.isCompleted = false;
  69842. }
  69843. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69844. var _this = this;
  69845. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  69846. _this.loadedMeshes = meshes;
  69847. _this.loadedParticleSystems = particleSystems;
  69848. _this.loadedSkeletons = skeletons;
  69849. _this.isCompleted = true;
  69850. if (_this.onSuccess) {
  69851. _this.onSuccess(_this);
  69852. }
  69853. onSuccess();
  69854. }, null, function (scene, message, exception) {
  69855. if (_this.onError) {
  69856. _this.onError(_this, message, exception);
  69857. }
  69858. onError(message, exception);
  69859. });
  69860. };
  69861. return MeshAssetTask;
  69862. }());
  69863. BABYLON.MeshAssetTask = MeshAssetTask;
  69864. var TextFileAssetTask = (function () {
  69865. function TextFileAssetTask(name, url) {
  69866. this.name = name;
  69867. this.url = url;
  69868. this.isCompleted = false;
  69869. }
  69870. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69871. var _this = this;
  69872. BABYLON.Tools.LoadFile(this.url, function (data) {
  69873. _this.text = data;
  69874. _this.isCompleted = true;
  69875. if (_this.onSuccess) {
  69876. _this.onSuccess(_this);
  69877. }
  69878. onSuccess();
  69879. }, null, scene.database, false, function (request, exception) {
  69880. if (_this.onError) {
  69881. _this.onError(_this, request.status + " " + request.statusText, exception);
  69882. }
  69883. onError(request.status + " " + request.statusText, exception);
  69884. });
  69885. };
  69886. return TextFileAssetTask;
  69887. }());
  69888. BABYLON.TextFileAssetTask = TextFileAssetTask;
  69889. var BinaryFileAssetTask = (function () {
  69890. function BinaryFileAssetTask(name, url) {
  69891. this.name = name;
  69892. this.url = url;
  69893. this.isCompleted = false;
  69894. }
  69895. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69896. var _this = this;
  69897. BABYLON.Tools.LoadFile(this.url, function (data) {
  69898. _this.data = data;
  69899. _this.isCompleted = true;
  69900. if (_this.onSuccess) {
  69901. _this.onSuccess(_this);
  69902. }
  69903. onSuccess();
  69904. }, null, scene.database, true, function (request, exception) {
  69905. if (_this.onError) {
  69906. _this.onError(_this, request.status + " " + request.statusText, exception);
  69907. }
  69908. onError(request.status + " " + request.statusText, exception);
  69909. });
  69910. };
  69911. return BinaryFileAssetTask;
  69912. }());
  69913. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  69914. var ImageAssetTask = (function () {
  69915. function ImageAssetTask(name, url) {
  69916. this.name = name;
  69917. this.url = url;
  69918. this.isCompleted = false;
  69919. }
  69920. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69921. var _this = this;
  69922. var img = new Image();
  69923. BABYLON.Tools.SetCorsBehavior(this.url, img);
  69924. img.onload = function () {
  69925. _this.image = img;
  69926. _this.isCompleted = true;
  69927. if (_this.onSuccess) {
  69928. _this.onSuccess(_this);
  69929. }
  69930. onSuccess();
  69931. };
  69932. img.onerror = function (err) {
  69933. if (_this.onError) {
  69934. _this.onError(_this, "Error loading image", err);
  69935. }
  69936. onError("Error loading image", err);
  69937. };
  69938. img.src = this.url;
  69939. };
  69940. return ImageAssetTask;
  69941. }());
  69942. BABYLON.ImageAssetTask = ImageAssetTask;
  69943. var TextureAssetTask = (function () {
  69944. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  69945. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69946. this.name = name;
  69947. this.url = url;
  69948. this.noMipmap = noMipmap;
  69949. this.invertY = invertY;
  69950. this.samplingMode = samplingMode;
  69951. this.isCompleted = false;
  69952. }
  69953. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69954. var _this = this;
  69955. var onload = function () {
  69956. _this.isCompleted = true;
  69957. if (_this.onSuccess) {
  69958. _this.onSuccess(_this);
  69959. }
  69960. onSuccess();
  69961. };
  69962. var onerror = function (msg, exception) {
  69963. if (_this.onError) {
  69964. _this.onError(_this, msg, exception);
  69965. }
  69966. onError(msg, exception);
  69967. };
  69968. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  69969. };
  69970. return TextureAssetTask;
  69971. }());
  69972. BABYLON.TextureAssetTask = TextureAssetTask;
  69973. var CubeTextureAssetTask = (function () {
  69974. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  69975. this.name = name;
  69976. this.url = url;
  69977. this.extensions = extensions;
  69978. this.noMipmap = noMipmap;
  69979. this.files = files;
  69980. this.isCompleted = false;
  69981. }
  69982. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69983. var _this = this;
  69984. var onload = function () {
  69985. _this.isCompleted = true;
  69986. if (_this.onSuccess) {
  69987. _this.onSuccess(_this);
  69988. }
  69989. onSuccess();
  69990. };
  69991. var onerror = function (msg, exception) {
  69992. if (_this.onError) {
  69993. _this.onError(_this, msg, exception);
  69994. }
  69995. onError(msg, exception);
  69996. };
  69997. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  69998. };
  69999. return CubeTextureAssetTask;
  70000. }());
  70001. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  70002. var HDRCubeTextureAssetTask = (function () {
  70003. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  70004. if (noMipmap === void 0) { noMipmap = false; }
  70005. if (generateHarmonics === void 0) { generateHarmonics = true; }
  70006. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  70007. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  70008. this.name = name;
  70009. this.url = url;
  70010. this.size = size;
  70011. this.noMipmap = noMipmap;
  70012. this.generateHarmonics = generateHarmonics;
  70013. this.useInGammaSpace = useInGammaSpace;
  70014. this.usePMREMGenerator = usePMREMGenerator;
  70015. this.isCompleted = false;
  70016. }
  70017. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  70018. var _this = this;
  70019. var onload = function () {
  70020. _this.isCompleted = true;
  70021. if (_this.onSuccess) {
  70022. _this.onSuccess(_this);
  70023. }
  70024. onSuccess();
  70025. };
  70026. var onerror = function (message, exception) {
  70027. if (_this.onError) {
  70028. _this.onError(_this, message, exception);
  70029. }
  70030. onError(message, exception);
  70031. };
  70032. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  70033. };
  70034. return HDRCubeTextureAssetTask;
  70035. }());
  70036. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  70037. var AssetsManager = (function () {
  70038. function AssetsManager(scene) {
  70039. this.tasks = new Array();
  70040. this.waitingTasksCount = 0;
  70041. //Observables
  70042. this.onTaskSuccessObservable = new BABYLON.Observable();
  70043. this.onTaskErrorObservable = new BABYLON.Observable();
  70044. this.onTasksDoneObservable = new BABYLON.Observable();
  70045. this.useDefaultLoadingScreen = true;
  70046. this._scene = scene;
  70047. }
  70048. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  70049. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  70050. this.tasks.push(task);
  70051. return task;
  70052. };
  70053. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  70054. var task = new TextFileAssetTask(taskName, url);
  70055. this.tasks.push(task);
  70056. return task;
  70057. };
  70058. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  70059. var task = new BinaryFileAssetTask(taskName, url);
  70060. this.tasks.push(task);
  70061. return task;
  70062. };
  70063. AssetsManager.prototype.addImageTask = function (taskName, url) {
  70064. var task = new ImageAssetTask(taskName, url);
  70065. this.tasks.push(task);
  70066. return task;
  70067. };
  70068. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  70069. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70070. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  70071. this.tasks.push(task);
  70072. return task;
  70073. };
  70074. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  70075. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  70076. this.tasks.push(task);
  70077. return task;
  70078. };
  70079. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  70080. if (noMipmap === void 0) { noMipmap = false; }
  70081. if (generateHarmonics === void 0) { generateHarmonics = true; }
  70082. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  70083. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  70084. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  70085. this.tasks.push(task);
  70086. return task;
  70087. };
  70088. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  70089. this.waitingTasksCount--;
  70090. if (this.waitingTasksCount === 0) {
  70091. if (this.onFinish) {
  70092. this.onFinish(this.tasks);
  70093. }
  70094. this._scene.getEngine().hideLoadingUI();
  70095. }
  70096. };
  70097. AssetsManager.prototype._runTask = function (task) {
  70098. var _this = this;
  70099. task.run(this._scene, function () {
  70100. if (_this.onTaskSuccess) {
  70101. _this.onTaskSuccess(task);
  70102. }
  70103. _this.onTaskSuccessObservable.notifyObservers(task);
  70104. _this._decreaseWaitingTasksCount();
  70105. }, function () {
  70106. if (_this.onTaskError) {
  70107. _this.onTaskError(task);
  70108. }
  70109. _this.onTaskErrorObservable.notifyObservers(task);
  70110. _this._decreaseWaitingTasksCount();
  70111. });
  70112. };
  70113. AssetsManager.prototype.reset = function () {
  70114. this.tasks = new Array();
  70115. return this;
  70116. };
  70117. AssetsManager.prototype.load = function () {
  70118. this.waitingTasksCount = this.tasks.length;
  70119. if (this.waitingTasksCount === 0) {
  70120. if (this.onFinish) {
  70121. this.onFinish(this.tasks);
  70122. }
  70123. this.onTasksDoneObservable.notifyObservers(this.tasks);
  70124. return this;
  70125. }
  70126. if (this.useDefaultLoadingScreen) {
  70127. this._scene.getEngine().displayLoadingUI();
  70128. }
  70129. for (var index = 0; index < this.tasks.length; index++) {
  70130. var task = this.tasks[index];
  70131. this._runTask(task);
  70132. }
  70133. return this;
  70134. };
  70135. return AssetsManager;
  70136. }());
  70137. BABYLON.AssetsManager = AssetsManager;
  70138. })(BABYLON || (BABYLON = {}));
  70139. //# sourceMappingURL=babylon.assetsManager.js.map
  70140. var BABYLON;
  70141. (function (BABYLON) {
  70142. var MapTexture = (function (_super) {
  70143. __extends(MapTexture, _super);
  70144. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  70145. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70146. if (useMipMap === void 0) { useMipMap = false; }
  70147. if (margin === void 0) { margin = 0; }
  70148. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  70149. _this.name = name;
  70150. _this._size = size;
  70151. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70152. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70153. // Create the rectPackMap that will allocate portion of the texture
  70154. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  70155. // Create the texture that will store the content
  70156. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  70157. return _this;
  70158. }
  70159. /**
  70160. * Allocate a rectangle of a given size in the texture map
  70161. * @param size the size of the rectangle to allocation
  70162. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  70163. */
  70164. MapTexture.prototype.allocateRect = function (size) {
  70165. return this._rectPackingMap.addRect(size);
  70166. };
  70167. /**
  70168. * Free a given rectangle from the texture map
  70169. * @param rectInfo the instance corresponding to the rect to free.
  70170. */
  70171. MapTexture.prototype.freeRect = function (rectInfo) {
  70172. if (rectInfo) {
  70173. rectInfo.freeContent();
  70174. }
  70175. };
  70176. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  70177. /**
  70178. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  70179. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  70180. * @returns {}
  70181. */
  70182. get: function () {
  70183. return this._rectPackingMap.freeSpace;
  70184. },
  70185. enumerable: true,
  70186. configurable: true
  70187. });
  70188. /**
  70189. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  70190. * 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.
  70191. * Don't forget to call unbindTexture when you're done rendering
  70192. * @param rect the zone to render to
  70193. * @param clear true to clear the portion's color/depth data
  70194. */
  70195. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  70196. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  70197. };
  70198. /**
  70199. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  70200. * 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.
  70201. * Don't forget to call unbindTexture when you're done rendering
  70202. * @param pos the position into the texture
  70203. * @param size the portion to fit the clip space to
  70204. * @param clear true to clear the portion's color/depth data
  70205. */
  70206. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  70207. var engine = this.getScene().getEngine();
  70208. engine.bindFramebuffer(this._texture);
  70209. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  70210. if (clear) {
  70211. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  70212. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  70213. }
  70214. };
  70215. /**
  70216. * Unbind the texture map from the rendering engine.
  70217. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  70218. * @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.
  70219. */
  70220. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  70221. // Dump ?
  70222. if (dumpForDebug) {
  70223. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  70224. }
  70225. var engine = this.getScene().getEngine();
  70226. if (this._replacedViewport) {
  70227. engine.setViewport(this._replacedViewport);
  70228. this._replacedViewport = null;
  70229. }
  70230. engine.unBindFramebuffer(this._texture);
  70231. };
  70232. Object.defineProperty(MapTexture.prototype, "canRescale", {
  70233. get: function () {
  70234. return false;
  70235. },
  70236. enumerable: true,
  70237. configurable: true
  70238. });
  70239. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  70240. // Anyway, there's not much point to use this method for this kind of texture I guess
  70241. MapTexture.prototype.clone = function () {
  70242. return null;
  70243. };
  70244. return MapTexture;
  70245. }(BABYLON.Texture));
  70246. BABYLON.MapTexture = MapTexture;
  70247. })(BABYLON || (BABYLON = {}));
  70248. //# sourceMappingURL=babylon.mapTexture.js.map
  70249. var BABYLON;
  70250. (function (BABYLON) {
  70251. /**
  70252. * This class describe a rectangle that were added to the map.
  70253. * You have access to its coordinates either in pixel or normalized (UV)
  70254. */
  70255. var PackedRect = (function () {
  70256. function PackedRect(root, parent, pos, size) {
  70257. this._pos = pos;
  70258. this._size = size;
  70259. this._root = root;
  70260. this._parent = parent;
  70261. this._contentSize = null;
  70262. this._bottomNode = null;
  70263. this._leftNode = null;
  70264. this._initialSize = null;
  70265. this._rightNode = null;
  70266. }
  70267. Object.defineProperty(PackedRect.prototype, "pos", {
  70268. /**
  70269. * @returns the position of this node into the map
  70270. */
  70271. get: function () {
  70272. return this._pos;
  70273. },
  70274. enumerable: true,
  70275. configurable: true
  70276. });
  70277. Object.defineProperty(PackedRect.prototype, "contentSize", {
  70278. /**
  70279. * @returns the size of the rectangle this node handles
  70280. */
  70281. get: function () {
  70282. return this._contentSize;
  70283. },
  70284. enumerable: true,
  70285. configurable: true
  70286. });
  70287. /**
  70288. * Retrieve the inner position (considering the margin) and stores it into the res object
  70289. * @param res must be a valid Vector2 that will contain the inner position after this call
  70290. */
  70291. PackedRect.prototype.getInnerPosToRef = function (res) {
  70292. var m = this._root._margin;
  70293. res.x = this._pos.x + m;
  70294. res.y = this._pos.y + m;
  70295. };
  70296. /**
  70297. * Retrieve the inner size (considering the margin) and stores it into the res object
  70298. * @param res must be a valid Size that will contain the inner size after this call
  70299. */
  70300. PackedRect.prototype.getInnerSizeToRef = function (res) {
  70301. var m = this._root._margin;
  70302. res.width = this._contentSize.width - (m * 2);
  70303. res.height = this._contentSize.height - (m * 2);
  70304. };
  70305. Object.defineProperty(PackedRect.prototype, "UVs", {
  70306. /**
  70307. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  70308. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  70309. */
  70310. get: function () {
  70311. if (!this._contentSize) {
  70312. throw new Error("Can't compute UVs for this object because it's nor allocated");
  70313. }
  70314. return this.getUVsForCustomSize(this._contentSize);
  70315. },
  70316. enumerable: true,
  70317. configurable: true
  70318. });
  70319. /**
  70320. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  70321. * and then using only a part of the PackRect.
  70322. * This method will return the UVs for this part by given the custom size of what you really use
  70323. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  70324. */
  70325. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  70326. var mainWidth = this._root._size.width;
  70327. var mainHeight = this._root._size.height;
  70328. var margin = this._root._margin;
  70329. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  70330. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  70331. var uvs = new Array();
  70332. uvs.push(topLeft);
  70333. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  70334. uvs.push(rightBottom);
  70335. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  70336. return uvs;
  70337. };
  70338. /**
  70339. * Free this rectangle from the map.
  70340. * Call this method when you no longer need the rectangle to be in the map.
  70341. */
  70342. PackedRect.prototype.freeContent = function () {
  70343. if (!this.contentSize) {
  70344. return;
  70345. }
  70346. this._contentSize = null;
  70347. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  70348. this.attemptDefrag();
  70349. };
  70350. Object.defineProperty(PackedRect.prototype, "isUsed", {
  70351. get: function () {
  70352. return this._contentSize != null || this._leftNode != null;
  70353. },
  70354. enumerable: true,
  70355. configurable: true
  70356. });
  70357. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  70358. var node = this.findNode(contentSize);
  70359. // Not enough space...
  70360. if (!node) {
  70361. return null;
  70362. }
  70363. node.splitNode(contentSize);
  70364. return node;
  70365. };
  70366. PackedRect.prototype.findNode = function (size) {
  70367. var resNode = null;
  70368. var margin = this._root._margin * 2;
  70369. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  70370. if (this.isUsed) {
  70371. if (this._leftNode) {
  70372. resNode = this._leftNode.findNode(size);
  70373. }
  70374. if (!resNode && this._rightNode) {
  70375. resNode = this._rightNode.findNode(size);
  70376. }
  70377. if (!resNode && this._bottomNode) {
  70378. resNode = this._bottomNode.findNode(size);
  70379. }
  70380. }
  70381. else if (this._initialSize) {
  70382. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  70383. resNode = this;
  70384. }
  70385. else {
  70386. return null;
  70387. }
  70388. }
  70389. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  70390. resNode = this;
  70391. }
  70392. return resNode;
  70393. };
  70394. PackedRect.prototype.splitNode = function (contentSize) {
  70395. var cs = PackedRect.TpsSize;
  70396. var margin = this._root._margin * 2;
  70397. cs.copyFrom(contentSize);
  70398. cs.width += margin;
  70399. cs.height += margin;
  70400. // 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)
  70401. if (!this._contentSize && this._initialSize) {
  70402. this._contentSize = cs.clone();
  70403. 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));
  70404. return this._leftNode.splitNode(contentSize);
  70405. }
  70406. else {
  70407. this._contentSize = cs.clone();
  70408. this._initialSize = cs.clone();
  70409. if (cs.width !== this._size.width) {
  70410. 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));
  70411. }
  70412. if (cs.height !== this._size.height) {
  70413. 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));
  70414. }
  70415. return this;
  70416. }
  70417. };
  70418. PackedRect.prototype.attemptDefrag = function () {
  70419. if (!this.isUsed && this.isRecursiveFree) {
  70420. this.clearNode();
  70421. if (this._parent) {
  70422. this._parent.attemptDefrag();
  70423. }
  70424. }
  70425. };
  70426. PackedRect.prototype.clearNode = function () {
  70427. this._initialSize = null;
  70428. this._rightNode = null;
  70429. this._bottomNode = null;
  70430. };
  70431. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  70432. get: function () {
  70433. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  70434. },
  70435. enumerable: true,
  70436. configurable: true
  70437. });
  70438. PackedRect.prototype.evalFreeSize = function (size) {
  70439. var levelSize = 0;
  70440. if (!this.isUsed) {
  70441. var margin = this._root._margin;
  70442. var is = this._initialSize;
  70443. if (is) {
  70444. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  70445. }
  70446. else {
  70447. var size_1 = this._size;
  70448. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  70449. }
  70450. }
  70451. if (this._rightNode) {
  70452. levelSize += this._rightNode.evalFreeSize(0);
  70453. }
  70454. if (this._bottomNode) {
  70455. levelSize += this._bottomNode.evalFreeSize(0);
  70456. }
  70457. return levelSize + size;
  70458. };
  70459. return PackedRect;
  70460. }());
  70461. PackedRect.TpsSize = BABYLON.Size.Zero();
  70462. BABYLON.PackedRect = PackedRect;
  70463. /**
  70464. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  70465. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  70466. * 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.
  70467. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  70468. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  70469. */
  70470. var RectPackingMap = (function (_super) {
  70471. __extends(RectPackingMap, _super);
  70472. /**
  70473. * Create an instance of the object with a dimension using the given size
  70474. * @param size The dimension of the rectangle that will contain all the sub ones.
  70475. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  70476. */
  70477. function RectPackingMap(size, margin) {
  70478. if (margin === void 0) { margin = 0; }
  70479. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  70480. _this._margin = margin;
  70481. _this._root = _this;
  70482. return _this;
  70483. }
  70484. /**
  70485. * Add a rectangle, finding the best location to store it into the map
  70486. * @param size the dimension of the rectangle to store
  70487. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  70488. */
  70489. RectPackingMap.prototype.addRect = function (size) {
  70490. var node = this.findAndSplitNode(size);
  70491. return node;
  70492. };
  70493. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  70494. /**
  70495. * Return the current space free normalized between [0;1]
  70496. * @returns {}
  70497. */
  70498. get: function () {
  70499. var freeSize = 0;
  70500. freeSize = this.evalFreeSize(freeSize);
  70501. return freeSize / (this._size.width * this._size.height);
  70502. },
  70503. enumerable: true,
  70504. configurable: true
  70505. });
  70506. return RectPackingMap;
  70507. }(PackedRect));
  70508. BABYLON.RectPackingMap = RectPackingMap;
  70509. })(BABYLON || (BABYLON = {}));
  70510. //# sourceMappingURL=babylon.rectPackingMap.js.map
  70511. var BABYLON;
  70512. (function (BABYLON) {
  70513. /**
  70514. * This groups together the common properties used for image processing either in direct forward pass
  70515. * or through post processing effect depending on the use of the image processing pipeline in your scene
  70516. * or not.
  70517. */
  70518. var ImageProcessingConfiguration = (function () {
  70519. function ImageProcessingConfiguration() {
  70520. /**
  70521. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  70522. */
  70523. this.colorCurves = new BABYLON.ColorCurves();
  70524. this._colorCurvesEnabled = false;
  70525. this._colorGradingEnabled = false;
  70526. this._colorGradingWithGreenDepth = false;
  70527. this._colorGradingBGR = false;
  70528. this._exposure = 1.0;
  70529. this._toneMappingEnabled = false;
  70530. this._contrast = 1.0;
  70531. /**
  70532. * Vignette stretch size.
  70533. */
  70534. this.vignetteStretch = 0;
  70535. /**
  70536. * Vignette centre X Offset.
  70537. */
  70538. this.vignetteCentreX = 0;
  70539. /**
  70540. * Vignette centre Y Offset.
  70541. */
  70542. this.vignetteCentreY = 0;
  70543. /**
  70544. * Vignette weight or intensity of the vignette effect.
  70545. */
  70546. this.vignetteWeight = 1.5;
  70547. /**
  70548. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70549. * if vignetteEnabled is set to true.
  70550. */
  70551. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  70552. /**
  70553. * Camera field of view used by the Vignette effect.
  70554. */
  70555. this.vignetteCameraFov = 0.5;
  70556. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  70557. this._vignetteEnabled = false;
  70558. this._applyByPostProcess = false;
  70559. /**
  70560. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  70561. * @type {BABYLON.Observable}
  70562. */
  70563. this.onUpdateParameters = new BABYLON.Observable();
  70564. }
  70565. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  70566. /**
  70567. * Gets wether the color curves effect is enabled.
  70568. */
  70569. get: function () {
  70570. return this._colorCurvesEnabled;
  70571. },
  70572. /**
  70573. * Sets wether the color curves effect is enabled.
  70574. */
  70575. set: function (value) {
  70576. if (this._colorCurvesEnabled === value) {
  70577. return;
  70578. }
  70579. this._colorCurvesEnabled = value;
  70580. this._updateParameters();
  70581. },
  70582. enumerable: true,
  70583. configurable: true
  70584. });
  70585. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  70586. /**
  70587. * Gets wether the color grading effect is enabled.
  70588. */
  70589. get: function () {
  70590. return this._colorGradingEnabled;
  70591. },
  70592. /**
  70593. * Sets wether the color grading effect is enabled.
  70594. */
  70595. set: function (value) {
  70596. if (this._colorGradingEnabled === value) {
  70597. return;
  70598. }
  70599. this._colorGradingEnabled = value;
  70600. this._updateParameters();
  70601. },
  70602. enumerable: true,
  70603. configurable: true
  70604. });
  70605. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  70606. /**
  70607. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  70608. */
  70609. get: function () {
  70610. return this._colorGradingWithGreenDepth;
  70611. },
  70612. /**
  70613. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  70614. */
  70615. set: function (value) {
  70616. if (this._colorGradingWithGreenDepth === value) {
  70617. return;
  70618. }
  70619. this._colorGradingWithGreenDepth = value;
  70620. this._updateParameters();
  70621. },
  70622. enumerable: true,
  70623. configurable: true
  70624. });
  70625. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  70626. /**
  70627. * Gets wether the color grading texture contains BGR values.
  70628. */
  70629. get: function () {
  70630. return this._colorGradingBGR;
  70631. },
  70632. /**
  70633. * Sets wether the color grading texture contains BGR values.
  70634. */
  70635. set: function (value) {
  70636. if (this._colorGradingBGR === value) {
  70637. return;
  70638. }
  70639. this._colorGradingBGR = value;
  70640. this._updateParameters();
  70641. },
  70642. enumerable: true,
  70643. configurable: true
  70644. });
  70645. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  70646. /**
  70647. * Gets the Exposure used in the effect.
  70648. */
  70649. get: function () {
  70650. return this._exposure;
  70651. },
  70652. /**
  70653. * Sets the Exposure used in the effect.
  70654. */
  70655. set: function (value) {
  70656. if (this._exposure === value) {
  70657. return;
  70658. }
  70659. this._exposure = value;
  70660. this._updateParameters();
  70661. },
  70662. enumerable: true,
  70663. configurable: true
  70664. });
  70665. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  70666. /**
  70667. * Gets wether the tone mapping effect is enabled.
  70668. */
  70669. get: function () {
  70670. return this._toneMappingEnabled;
  70671. },
  70672. /**
  70673. * Sets wether the tone mapping effect is enabled.
  70674. */
  70675. set: function (value) {
  70676. if (this._toneMappingEnabled === value) {
  70677. return;
  70678. }
  70679. this._toneMappingEnabled = value;
  70680. this._updateParameters();
  70681. },
  70682. enumerable: true,
  70683. configurable: true
  70684. });
  70685. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  70686. /**
  70687. * Gets the contrast used in the effect.
  70688. */
  70689. get: function () {
  70690. return this._contrast;
  70691. },
  70692. /**
  70693. * Sets the contrast used in the effect.
  70694. */
  70695. set: function (value) {
  70696. if (this._contrast === value) {
  70697. return;
  70698. }
  70699. this._contrast = value;
  70700. this._updateParameters();
  70701. },
  70702. enumerable: true,
  70703. configurable: true
  70704. });
  70705. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  70706. /**
  70707. * Gets the vignette blend mode allowing different kind of effect.
  70708. */
  70709. get: function () {
  70710. return this._vignetteBlendMode;
  70711. },
  70712. /**
  70713. * Sets the vignette blend mode allowing different kind of effect.
  70714. */
  70715. set: function (value) {
  70716. if (this._vignetteBlendMode === value) {
  70717. return;
  70718. }
  70719. this._vignetteBlendMode = value;
  70720. this._updateParameters();
  70721. },
  70722. enumerable: true,
  70723. configurable: true
  70724. });
  70725. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  70726. /**
  70727. * Gets wether the vignette effect is enabled.
  70728. */
  70729. get: function () {
  70730. return this._vignetteEnabled;
  70731. },
  70732. /**
  70733. * Sets wether the vignette effect is enabled.
  70734. */
  70735. set: function (value) {
  70736. if (this._vignetteEnabled === value) {
  70737. return;
  70738. }
  70739. this._vignetteEnabled = value;
  70740. this._updateParameters();
  70741. },
  70742. enumerable: true,
  70743. configurable: true
  70744. });
  70745. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  70746. /**
  70747. * Gets wether the image processing is applied through a post process or not.
  70748. */
  70749. get: function () {
  70750. return this._applyByPostProcess;
  70751. },
  70752. /**
  70753. * Sets wether the image processing is applied through a post process or not.
  70754. */
  70755. set: function (value) {
  70756. if (this._applyByPostProcess === value) {
  70757. return;
  70758. }
  70759. this._applyByPostProcess = value;
  70760. this._updateParameters();
  70761. },
  70762. enumerable: true,
  70763. configurable: true
  70764. });
  70765. /**
  70766. * Method called each time the image processing information changes requires to recompile the effect.
  70767. */
  70768. ImageProcessingConfiguration.prototype._updateParameters = function () {
  70769. this.onUpdateParameters.notifyObservers(this);
  70770. };
  70771. ImageProcessingConfiguration.prototype.getClassName = function () {
  70772. return "ImageProcessingConfiguration";
  70773. };
  70774. /**
  70775. * Prepare the list of uniforms associated with the Image Processing effects.
  70776. * @param uniformsList The list of uniforms used in the effect
  70777. * @param defines the list of defines currently in use
  70778. */
  70779. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  70780. if (defines.EXPOSURE) {
  70781. uniforms.push("exposureLinear");
  70782. }
  70783. if (defines.CONTRAST) {
  70784. uniforms.push("contrast");
  70785. }
  70786. if (defines.COLORGRADING) {
  70787. uniforms.push("colorTransformSettings");
  70788. }
  70789. if (defines.VIGNETTE) {
  70790. uniforms.push("vInverseScreenSize");
  70791. uniforms.push("vignetteSettings1");
  70792. uniforms.push("vignetteSettings2");
  70793. }
  70794. if (defines.COLORCURVES) {
  70795. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  70796. }
  70797. };
  70798. /**
  70799. * Prepare the list of samplers associated with the Image Processing effects.
  70800. * @param uniformsList The list of uniforms used in the effect
  70801. * @param defines the list of defines currently in use
  70802. */
  70803. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  70804. if (defines.COLORGRADING) {
  70805. samplersList.push("txColorTransform");
  70806. }
  70807. };
  70808. /**
  70809. * Prepare the list of defines associated to the shader.
  70810. * @param defines the list of defines to complete
  70811. */
  70812. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  70813. if (forPostProcess === void 0) { forPostProcess = false; }
  70814. if (forPostProcess !== this.applyByPostProcess) {
  70815. defines.VIGNETTE = false;
  70816. defines.TONEMAPPING = false;
  70817. defines.CONTRAST = false;
  70818. defines.EXPOSURE = false;
  70819. defines.COLORCURVES = false;
  70820. defines.COLORGRADING = false;
  70821. defines.IMAGEPROCESSING = false;
  70822. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  70823. return;
  70824. }
  70825. defines.VIGNETTE = this.vignetteEnabled;
  70826. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  70827. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  70828. defines.TONEMAPPING = this.toneMappingEnabled;
  70829. defines.CONTRAST = (this.contrast !== 1.0);
  70830. defines.EXPOSURE = (this.exposure !== 1.0);
  70831. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  70832. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  70833. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  70834. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  70835. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  70836. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  70837. };
  70838. /**
  70839. * Returns true if all the image processing information are ready.
  70840. */
  70841. ImageProcessingConfiguration.prototype.isReady = function () {
  70842. // Color Grading texure can not be none blocking.
  70843. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  70844. };
  70845. /**
  70846. * Binds the image processing to the shader.
  70847. * @param effect The effect to bind to
  70848. */
  70849. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  70850. if (aspectRatio === void 0) { aspectRatio = 1; }
  70851. // Color Curves
  70852. if (this._colorCurvesEnabled) {
  70853. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  70854. }
  70855. // Vignette
  70856. if (this._vignetteEnabled) {
  70857. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  70858. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  70859. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  70860. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  70861. var vignetteScaleX = vignetteScaleY * aspectRatio;
  70862. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  70863. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  70864. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  70865. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  70866. var vignettePower = -2.0 * this.vignetteWeight;
  70867. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  70868. }
  70869. // Exposure
  70870. effect.setFloat("exposureLinear", this.exposure);
  70871. // Contrast
  70872. effect.setFloat("contrast", this.contrast);
  70873. // Color transform settings
  70874. if (this.colorGradingTexture) {
  70875. effect.setTexture("txColorTransform", this.colorGradingTexture);
  70876. var textureSize = this.colorGradingTexture.getSize().height;
  70877. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  70878. 0.5 / textureSize, // textureOffset
  70879. textureSize, // textureSize
  70880. this.colorGradingTexture.level // weight
  70881. );
  70882. }
  70883. };
  70884. /**
  70885. * Clones the current image processing instance.
  70886. * @return The cloned image processing
  70887. */
  70888. ImageProcessingConfiguration.prototype.clone = function () {
  70889. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  70890. };
  70891. /**
  70892. * Serializes the current image processing instance to a json representation.
  70893. * @return a JSON representation
  70894. */
  70895. ImageProcessingConfiguration.prototype.serialize = function () {
  70896. return BABYLON.SerializationHelper.Serialize(this);
  70897. };
  70898. /**
  70899. * Parses the image processing from a json representation.
  70900. * @param source the JSON source to parse
  70901. * @return The parsed image processing
  70902. */
  70903. ImageProcessingConfiguration.Parse = function (source) {
  70904. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  70905. };
  70906. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  70907. /**
  70908. * Used to apply the vignette as a mix with the pixel color.
  70909. */
  70910. get: function () {
  70911. return this._VIGNETTEMODE_MULTIPLY;
  70912. },
  70913. enumerable: true,
  70914. configurable: true
  70915. });
  70916. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  70917. /**
  70918. * Used to apply the vignette as a replacement of the pixel color.
  70919. */
  70920. get: function () {
  70921. return this._VIGNETTEMODE_OPAQUE;
  70922. },
  70923. enumerable: true,
  70924. configurable: true
  70925. });
  70926. return ImageProcessingConfiguration;
  70927. }());
  70928. // Static constants associated to the image processing.
  70929. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  70930. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  70931. __decorate([
  70932. BABYLON.serializeAsColorCurves()
  70933. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  70934. __decorate([
  70935. BABYLON.serialize()
  70936. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  70937. __decorate([
  70938. BABYLON.serializeAsTexture()
  70939. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  70940. __decorate([
  70941. BABYLON.serialize()
  70942. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  70943. __decorate([
  70944. BABYLON.serialize()
  70945. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  70946. __decorate([
  70947. BABYLON.serialize()
  70948. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  70949. __decorate([
  70950. BABYLON.serialize()
  70951. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  70952. __decorate([
  70953. BABYLON.serialize()
  70954. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  70955. __decorate([
  70956. BABYLON.serialize()
  70957. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  70958. __decorate([
  70959. BABYLON.serialize()
  70960. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  70961. __decorate([
  70962. BABYLON.serialize()
  70963. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  70964. __decorate([
  70965. BABYLON.serialize()
  70966. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  70967. __decorate([
  70968. BABYLON.serialize()
  70969. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  70970. __decorate([
  70971. BABYLON.serializeAsColor4()
  70972. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  70973. __decorate([
  70974. BABYLON.serialize()
  70975. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  70976. __decorate([
  70977. BABYLON.serialize()
  70978. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  70979. __decorate([
  70980. BABYLON.serialize()
  70981. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  70982. __decorate([
  70983. BABYLON.serialize()
  70984. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  70985. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  70986. })(BABYLON || (BABYLON = {}));
  70987. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  70988. var BABYLON;
  70989. (function (BABYLON) {
  70990. var serializedGeometries = [];
  70991. var serializeGeometry = function (geometry, serializationGeometries) {
  70992. if (serializedGeometries[geometry.id]) {
  70993. return;
  70994. }
  70995. if (geometry.doNotSerialize) {
  70996. return;
  70997. }
  70998. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  70999. serializationGeometries.boxes.push(geometry.serialize());
  71000. }
  71001. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  71002. serializationGeometries.spheres.push(geometry.serialize());
  71003. }
  71004. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  71005. serializationGeometries.cylinders.push(geometry.serialize());
  71006. }
  71007. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  71008. serializationGeometries.toruses.push(geometry.serialize());
  71009. }
  71010. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  71011. serializationGeometries.grounds.push(geometry.serialize());
  71012. }
  71013. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  71014. serializationGeometries.planes.push(geometry.serialize());
  71015. }
  71016. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  71017. serializationGeometries.torusKnots.push(geometry.serialize());
  71018. }
  71019. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  71020. throw new Error("Unknown primitive type");
  71021. }
  71022. else {
  71023. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  71024. }
  71025. serializedGeometries[geometry.id] = true;
  71026. };
  71027. var serializeMesh = function (mesh, serializationScene) {
  71028. var serializationObject = {};
  71029. // Geometry
  71030. var geometry = mesh._geometry;
  71031. if (geometry) {
  71032. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  71033. // 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
  71034. serializeGeometry(geometry, serializationScene.geometries);
  71035. }
  71036. }
  71037. // Custom
  71038. if (mesh.serialize) {
  71039. mesh.serialize(serializationObject);
  71040. }
  71041. return serializationObject;
  71042. };
  71043. var finalizeSingleMesh = function (mesh, serializationObject) {
  71044. //only works if the mesh is already loaded
  71045. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  71046. //serialize material
  71047. if (mesh.material) {
  71048. if (mesh.material instanceof BABYLON.StandardMaterial) {
  71049. serializationObject.materials = serializationObject.materials || [];
  71050. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  71051. serializationObject.materials.push(mesh.material.serialize());
  71052. }
  71053. }
  71054. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  71055. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  71056. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  71057. serializationObject.multiMaterials.push(mesh.material.serialize());
  71058. }
  71059. }
  71060. }
  71061. //serialize geometry
  71062. var geometry = mesh._geometry;
  71063. if (geometry) {
  71064. if (!serializationObject.geometries) {
  71065. serializationObject.geometries = {};
  71066. serializationObject.geometries.boxes = [];
  71067. serializationObject.geometries.spheres = [];
  71068. serializationObject.geometries.cylinders = [];
  71069. serializationObject.geometries.toruses = [];
  71070. serializationObject.geometries.grounds = [];
  71071. serializationObject.geometries.planes = [];
  71072. serializationObject.geometries.torusKnots = [];
  71073. serializationObject.geometries.vertexData = [];
  71074. }
  71075. serializeGeometry(geometry, serializationObject.geometries);
  71076. }
  71077. // Skeletons
  71078. if (mesh.skeleton) {
  71079. serializationObject.skeletons = serializationObject.skeletons || [];
  71080. serializationObject.skeletons.push(mesh.skeleton.serialize());
  71081. }
  71082. //serialize the actual mesh
  71083. serializationObject.meshes = serializationObject.meshes || [];
  71084. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  71085. }
  71086. };
  71087. var SceneSerializer = (function () {
  71088. function SceneSerializer() {
  71089. }
  71090. SceneSerializer.ClearCache = function () {
  71091. serializedGeometries = [];
  71092. };
  71093. SceneSerializer.Serialize = function (scene) {
  71094. var serializationObject = {};
  71095. SceneSerializer.ClearCache();
  71096. // Scene
  71097. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  71098. serializationObject.autoClear = scene.autoClear;
  71099. serializationObject.clearColor = scene.clearColor.asArray();
  71100. serializationObject.ambientColor = scene.ambientColor.asArray();
  71101. serializationObject.gravity = scene.gravity.asArray();
  71102. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  71103. serializationObject.workerCollisions = scene.workerCollisions;
  71104. // Fog
  71105. if (scene.fogMode && scene.fogMode !== 0) {
  71106. serializationObject.fogMode = scene.fogMode;
  71107. serializationObject.fogColor = scene.fogColor.asArray();
  71108. serializationObject.fogStart = scene.fogStart;
  71109. serializationObject.fogEnd = scene.fogEnd;
  71110. serializationObject.fogDensity = scene.fogDensity;
  71111. }
  71112. //Physics
  71113. if (scene.isPhysicsEnabled()) {
  71114. serializationObject.physicsEnabled = true;
  71115. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  71116. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  71117. }
  71118. // Metadata
  71119. if (scene.metadata) {
  71120. serializationObject.metadata = scene.metadata;
  71121. }
  71122. // Morph targets
  71123. serializationObject.morphTargetManagers = [];
  71124. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  71125. var abstractMesh = _a[_i];
  71126. var manager = abstractMesh.morphTargetManager;
  71127. if (manager) {
  71128. serializationObject.morphTargetManagers.push(manager.serialize());
  71129. }
  71130. }
  71131. // Lights
  71132. serializationObject.lights = [];
  71133. var index;
  71134. var light;
  71135. for (index = 0; index < scene.lights.length; index++) {
  71136. light = scene.lights[index];
  71137. if (!light.doNotSerialize) {
  71138. serializationObject.lights.push(light.serialize());
  71139. }
  71140. }
  71141. // Cameras
  71142. serializationObject.cameras = [];
  71143. for (index = 0; index < scene.cameras.length; index++) {
  71144. var camera = scene.cameras[index];
  71145. if (!camera.doNotSerialize) {
  71146. serializationObject.cameras.push(camera.serialize());
  71147. }
  71148. }
  71149. if (scene.activeCamera) {
  71150. serializationObject.activeCameraID = scene.activeCamera.id;
  71151. }
  71152. // Animations
  71153. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  71154. // Materials
  71155. serializationObject.materials = [];
  71156. serializationObject.multiMaterials = [];
  71157. var material;
  71158. for (index = 0; index < scene.materials.length; index++) {
  71159. material = scene.materials[index];
  71160. if (!material.doNotSerialize) {
  71161. serializationObject.materials.push(material.serialize());
  71162. }
  71163. }
  71164. // MultiMaterials
  71165. serializationObject.multiMaterials = [];
  71166. for (index = 0; index < scene.multiMaterials.length; index++) {
  71167. var multiMaterial = scene.multiMaterials[index];
  71168. serializationObject.multiMaterials.push(multiMaterial.serialize());
  71169. }
  71170. // Skeletons
  71171. serializationObject.skeletons = [];
  71172. for (index = 0; index < scene.skeletons.length; index++) {
  71173. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  71174. }
  71175. // Geometries
  71176. serializationObject.geometries = {};
  71177. serializationObject.geometries.boxes = [];
  71178. serializationObject.geometries.spheres = [];
  71179. serializationObject.geometries.cylinders = [];
  71180. serializationObject.geometries.toruses = [];
  71181. serializationObject.geometries.grounds = [];
  71182. serializationObject.geometries.planes = [];
  71183. serializationObject.geometries.torusKnots = [];
  71184. serializationObject.geometries.vertexData = [];
  71185. serializedGeometries = [];
  71186. var geometries = scene.getGeometries();
  71187. for (index = 0; index < geometries.length; index++) {
  71188. var geometry = geometries[index];
  71189. if (geometry.isReady()) {
  71190. serializeGeometry(geometry, serializationObject.geometries);
  71191. }
  71192. }
  71193. // Meshes
  71194. serializationObject.meshes = [];
  71195. for (index = 0; index < scene.meshes.length; index++) {
  71196. var abstractMesh = scene.meshes[index];
  71197. if (abstractMesh instanceof BABYLON.Mesh) {
  71198. var mesh = abstractMesh;
  71199. if (!mesh.doNotSerialize) {
  71200. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  71201. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  71202. }
  71203. }
  71204. }
  71205. }
  71206. // Particles Systems
  71207. serializationObject.particleSystems = [];
  71208. for (index = 0; index < scene.particleSystems.length; index++) {
  71209. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  71210. }
  71211. // Lens flares
  71212. serializationObject.lensFlareSystems = [];
  71213. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  71214. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  71215. }
  71216. // Shadows
  71217. serializationObject.shadowGenerators = [];
  71218. for (index = 0; index < scene.lights.length; index++) {
  71219. light = scene.lights[index];
  71220. var shadowGenerator = light.getShadowGenerator();
  71221. if (shadowGenerator) {
  71222. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  71223. }
  71224. }
  71225. // Action Manager
  71226. if (scene.actionManager) {
  71227. serializationObject.actions = scene.actionManager.serialize("scene");
  71228. }
  71229. // Audio
  71230. serializationObject.sounds = [];
  71231. for (index = 0; index < scene.soundTracks.length; index++) {
  71232. var soundtrack = scene.soundTracks[index];
  71233. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  71234. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  71235. }
  71236. }
  71237. return serializationObject;
  71238. };
  71239. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  71240. if (withParents === void 0) { withParents = false; }
  71241. if (withChildren === void 0) { withChildren = false; }
  71242. var serializationObject = {};
  71243. SceneSerializer.ClearCache();
  71244. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  71245. if (withParents || withChildren) {
  71246. //deliberate for loop! not for each, appended should be processed as well.
  71247. for (var i = 0; i < toSerialize.length; ++i) {
  71248. if (withChildren) {
  71249. toSerialize[i].getDescendants().forEach(function (node) {
  71250. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  71251. toSerialize.push(node);
  71252. }
  71253. });
  71254. }
  71255. //make sure the array doesn't contain the object already
  71256. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  71257. toSerialize.push(toSerialize[i].parent);
  71258. }
  71259. }
  71260. }
  71261. toSerialize.forEach(function (mesh) {
  71262. finalizeSingleMesh(mesh, serializationObject);
  71263. });
  71264. return serializationObject;
  71265. };
  71266. return SceneSerializer;
  71267. }());
  71268. BABYLON.SceneSerializer = SceneSerializer;
  71269. })(BABYLON || (BABYLON = {}));
  71270. //# sourceMappingURL=babylon.sceneSerializer.js.map
  71271. var BABYLON;
  71272. (function (BABYLON) {
  71273. var ReflectionProbe = (function () {
  71274. function ReflectionProbe(name, size, scene, generateMipMaps) {
  71275. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71276. var _this = this;
  71277. this.name = name;
  71278. this._viewMatrix = BABYLON.Matrix.Identity();
  71279. this._target = BABYLON.Vector3.Zero();
  71280. this._add = BABYLON.Vector3.Zero();
  71281. this.invertYAxis = false;
  71282. this.position = BABYLON.Vector3.Zero();
  71283. this._scene = scene;
  71284. this._scene.reflectionProbes.push(this);
  71285. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  71286. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  71287. switch (faceIndex) {
  71288. case 0:
  71289. _this._add.copyFromFloats(1, 0, 0);
  71290. break;
  71291. case 1:
  71292. _this._add.copyFromFloats(-1, 0, 0);
  71293. break;
  71294. case 2:
  71295. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  71296. break;
  71297. case 3:
  71298. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  71299. break;
  71300. case 4:
  71301. _this._add.copyFromFloats(0, 0, 1);
  71302. break;
  71303. case 5:
  71304. _this._add.copyFromFloats(0, 0, -1);
  71305. break;
  71306. }
  71307. if (_this._attachedMesh) {
  71308. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  71309. }
  71310. _this.position.addToRef(_this._add, _this._target);
  71311. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  71312. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  71313. });
  71314. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  71315. scene.updateTransformMatrix(true);
  71316. });
  71317. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  71318. }
  71319. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  71320. get: function () {
  71321. return this._renderTargetTexture.samples;
  71322. },
  71323. set: function (value) {
  71324. this._renderTargetTexture.samples = value;
  71325. },
  71326. enumerable: true,
  71327. configurable: true
  71328. });
  71329. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  71330. get: function () {
  71331. return this._renderTargetTexture.refreshRate;
  71332. },
  71333. set: function (value) {
  71334. this._renderTargetTexture.refreshRate = value;
  71335. },
  71336. enumerable: true,
  71337. configurable: true
  71338. });
  71339. ReflectionProbe.prototype.getScene = function () {
  71340. return this._scene;
  71341. };
  71342. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  71343. get: function () {
  71344. return this._renderTargetTexture;
  71345. },
  71346. enumerable: true,
  71347. configurable: true
  71348. });
  71349. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  71350. get: function () {
  71351. return this._renderTargetTexture.renderList;
  71352. },
  71353. enumerable: true,
  71354. configurable: true
  71355. });
  71356. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  71357. this._attachedMesh = mesh;
  71358. };
  71359. /**
  71360. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  71361. *
  71362. * @param renderingGroupId The rendering group id corresponding to its index
  71363. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  71364. */
  71365. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  71366. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  71367. };
  71368. ReflectionProbe.prototype.dispose = function () {
  71369. var index = this._scene.reflectionProbes.indexOf(this);
  71370. if (index !== -1) {
  71371. // Remove from the scene if found
  71372. this._scene.reflectionProbes.splice(index, 1);
  71373. }
  71374. if (this._renderTargetTexture) {
  71375. this._renderTargetTexture.dispose();
  71376. this._renderTargetTexture = null;
  71377. }
  71378. };
  71379. return ReflectionProbe;
  71380. }());
  71381. BABYLON.ReflectionProbe = ReflectionProbe;
  71382. })(BABYLON || (BABYLON = {}));
  71383. //# sourceMappingURL=babylon.reflectionProbe.js.map
  71384. var BABYLON;
  71385. (function (BABYLON) {
  71386. var Layer = (function () {
  71387. function Layer(name, imgUrl, scene, isBackground, color) {
  71388. this.name = name;
  71389. this.scale = new BABYLON.Vector2(1, 1);
  71390. this.offset = new BABYLON.Vector2(0, 0);
  71391. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  71392. this.layerMask = 0x0FFFFFFF;
  71393. this._vertexBuffers = {};
  71394. // Events
  71395. /**
  71396. * An event triggered when the layer is disposed.
  71397. * @type {BABYLON.Observable}
  71398. */
  71399. this.onDisposeObservable = new BABYLON.Observable();
  71400. /**
  71401. * An event triggered before rendering the scene
  71402. * @type {BABYLON.Observable}
  71403. */
  71404. this.onBeforeRenderObservable = new BABYLON.Observable();
  71405. /**
  71406. * An event triggered after rendering the scene
  71407. * @type {BABYLON.Observable}
  71408. */
  71409. this.onAfterRenderObservable = new BABYLON.Observable();
  71410. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  71411. this.isBackground = isBackground === undefined ? true : isBackground;
  71412. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  71413. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71414. this._scene.layers.push(this);
  71415. var engine = this._scene.getEngine();
  71416. // VBO
  71417. var vertices = [];
  71418. vertices.push(1, 1);
  71419. vertices.push(-1, 1);
  71420. vertices.push(-1, -1);
  71421. vertices.push(1, -1);
  71422. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71423. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  71424. this._createIndexBuffer();
  71425. // Effects
  71426. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  71427. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  71428. }
  71429. Object.defineProperty(Layer.prototype, "onDispose", {
  71430. set: function (callback) {
  71431. if (this._onDisposeObserver) {
  71432. this.onDisposeObservable.remove(this._onDisposeObserver);
  71433. }
  71434. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  71435. },
  71436. enumerable: true,
  71437. configurable: true
  71438. });
  71439. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  71440. set: function (callback) {
  71441. if (this._onBeforeRenderObserver) {
  71442. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71443. }
  71444. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71445. },
  71446. enumerable: true,
  71447. configurable: true
  71448. });
  71449. Object.defineProperty(Layer.prototype, "onAfterRender", {
  71450. set: function (callback) {
  71451. if (this._onAfterRenderObserver) {
  71452. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71453. }
  71454. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71455. },
  71456. enumerable: true,
  71457. configurable: true
  71458. });
  71459. Layer.prototype._createIndexBuffer = function () {
  71460. var engine = this._scene.getEngine();
  71461. // Indices
  71462. var indices = [];
  71463. indices.push(0);
  71464. indices.push(1);
  71465. indices.push(2);
  71466. indices.push(0);
  71467. indices.push(2);
  71468. indices.push(3);
  71469. this._indexBuffer = engine.createIndexBuffer(indices);
  71470. };
  71471. Layer.prototype._rebuild = function () {
  71472. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  71473. this._createIndexBuffer();
  71474. };
  71475. Layer.prototype.render = function () {
  71476. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  71477. // Check
  71478. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  71479. return;
  71480. var engine = this._scene.getEngine();
  71481. this.onBeforeRenderObservable.notifyObservers(this);
  71482. // Render
  71483. engine.enableEffect(currentEffect);
  71484. engine.setState(false);
  71485. // Texture
  71486. currentEffect.setTexture("textureSampler", this.texture);
  71487. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  71488. // Color
  71489. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  71490. // Scale / offset
  71491. currentEffect.setVector2("offset", this.offset);
  71492. currentEffect.setVector2("scale", this.scale);
  71493. // VBOs
  71494. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  71495. // Draw order
  71496. if (!this.alphaTest) {
  71497. engine.setAlphaMode(this.alphaBlendingMode);
  71498. engine.draw(true, 0, 6);
  71499. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71500. }
  71501. else {
  71502. engine.draw(true, 0, 6);
  71503. }
  71504. this.onAfterRenderObservable.notifyObservers(this);
  71505. };
  71506. Layer.prototype.dispose = function () {
  71507. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71508. if (vertexBuffer) {
  71509. vertexBuffer.dispose();
  71510. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71511. }
  71512. if (this._indexBuffer) {
  71513. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71514. this._indexBuffer = null;
  71515. }
  71516. if (this.texture) {
  71517. this.texture.dispose();
  71518. this.texture = null;
  71519. }
  71520. // Remove from scene
  71521. var index = this._scene.layers.indexOf(this);
  71522. this._scene.layers.splice(index, 1);
  71523. // Callback
  71524. this.onDisposeObservable.notifyObservers(this);
  71525. this.onDisposeObservable.clear();
  71526. this.onAfterRenderObservable.clear();
  71527. this.onBeforeRenderObservable.clear();
  71528. };
  71529. return Layer;
  71530. }());
  71531. BABYLON.Layer = Layer;
  71532. })(BABYLON || (BABYLON = {}));
  71533. //# sourceMappingURL=babylon.layer.js.map
  71534. var BABYLON;
  71535. (function (BABYLON) {
  71536. var TextureTools = (function () {
  71537. function TextureTools() {
  71538. }
  71539. /**
  71540. * Uses the GPU to create a copy texture rescaled at a given size
  71541. * @param texture Texture to copy from
  71542. * @param width Desired width
  71543. * @param height Desired height
  71544. * @return Generated texture
  71545. */
  71546. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  71547. if (useBilinearMode === void 0) { useBilinearMode = true; }
  71548. var scene = texture.getScene();
  71549. var engine = scene.getEngine();
  71550. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  71551. rtt.wrapU = texture.wrapU;
  71552. rtt.wrapV = texture.wrapV;
  71553. rtt.uOffset = texture.uOffset;
  71554. rtt.vOffset = texture.vOffset;
  71555. rtt.uScale = texture.uScale;
  71556. rtt.vScale = texture.vScale;
  71557. rtt.uAng = texture.uAng;
  71558. rtt.vAng = texture.vAng;
  71559. rtt.wAng = texture.wAng;
  71560. rtt.coordinatesIndex = texture.coordinatesIndex;
  71561. rtt.level = texture.level;
  71562. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  71563. rtt._texture.isReady = false;
  71564. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71565. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71566. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71567. passPostProcess.getEffect().executeWhenCompiled(function () {
  71568. passPostProcess.onApply = function (effect) {
  71569. effect.setTexture("textureSampler", texture);
  71570. };
  71571. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  71572. engine.unBindFramebuffer(rtt.getInternalTexture());
  71573. rtt.disposeFramebufferObjects();
  71574. passPostProcess.dispose();
  71575. rtt._texture.isReady = true;
  71576. });
  71577. return rtt;
  71578. };
  71579. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  71580. if (!scene._environmentBRDFTexture) {
  71581. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71582. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71583. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71584. scene._environmentBRDFTexture = texture;
  71585. }
  71586. return scene._environmentBRDFTexture;
  71587. };
  71588. return TextureTools;
  71589. }());
  71590. 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=";
  71591. BABYLON.TextureTools = TextureTools;
  71592. })(BABYLON || (BABYLON = {}));
  71593. //# sourceMappingURL=babylon.textureTools.js.map
  71594. var BABYLON;
  71595. (function (BABYLON) {
  71596. var FramingBehavior = (function () {
  71597. function FramingBehavior() {
  71598. this._mode = FramingBehavior.FitFrustumSidesMode;
  71599. this._radiusScale = 1.0;
  71600. this._positionScale = 0.5;
  71601. this._defaultElevation = 0.3;
  71602. this._elevationReturnTime = 1500;
  71603. this._elevationReturnWaitTime = 1000;
  71604. this._zoomStopsAnimation = false;
  71605. this._framingTime = 1500;
  71606. this._isPointerDown = false;
  71607. this._lastFrameTime = null;
  71608. this._lastInteractionTime = -Infinity;
  71609. // Framing control
  71610. this._animatables = new Array();
  71611. this._betaIsAnimating = false;
  71612. this._lastFrameRadius = 0;
  71613. }
  71614. Object.defineProperty(FramingBehavior.prototype, "name", {
  71615. get: function () {
  71616. return "Framing";
  71617. },
  71618. enumerable: true,
  71619. configurable: true
  71620. });
  71621. Object.defineProperty(FramingBehavior.prototype, "mode", {
  71622. /**
  71623. * Gets current mode used by the behavior.
  71624. */
  71625. get: function () {
  71626. return this._mode;
  71627. },
  71628. /**
  71629. * Sets the current mode used by the behavior
  71630. */
  71631. set: function (mode) {
  71632. this._mode = mode;
  71633. },
  71634. enumerable: true,
  71635. configurable: true
  71636. });
  71637. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  71638. /**
  71639. * Gets the scale applied to the radius
  71640. */
  71641. get: function () {
  71642. return this._radiusScale;
  71643. },
  71644. /**
  71645. * Sets the scale applied to the radius (1 by default)
  71646. */
  71647. set: function (radius) {
  71648. this._radiusScale = radius;
  71649. },
  71650. enumerable: true,
  71651. configurable: true
  71652. });
  71653. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  71654. /**
  71655. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  71656. */
  71657. get: function () {
  71658. return this._positionScale;
  71659. },
  71660. /**
  71661. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  71662. */
  71663. set: function (scale) {
  71664. this._positionScale = scale;
  71665. },
  71666. enumerable: true,
  71667. configurable: true
  71668. });
  71669. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  71670. /**
  71671. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  71672. * behaviour is triggered, in radians.
  71673. */
  71674. get: function () {
  71675. return this._defaultElevation;
  71676. },
  71677. /**
  71678. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  71679. * behaviour is triggered, in radians.
  71680. */
  71681. set: function (elevation) {
  71682. this._defaultElevation = elevation;
  71683. },
  71684. enumerable: true,
  71685. configurable: true
  71686. });
  71687. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  71688. /**
  71689. * Gets the time (in milliseconds) taken to return to the default beta position.
  71690. * Negative value indicates camera should not return to default.
  71691. */
  71692. get: function () {
  71693. return this._elevationReturnTime;
  71694. },
  71695. /**
  71696. * Sets the time (in milliseconds) taken to return to the default beta position.
  71697. * Negative value indicates camera should not return to default.
  71698. */
  71699. set: function (speed) {
  71700. this._elevationReturnTime = speed;
  71701. },
  71702. enumerable: true,
  71703. configurable: true
  71704. });
  71705. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  71706. /**
  71707. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  71708. */
  71709. get: function () {
  71710. return this._elevationReturnWaitTime;
  71711. },
  71712. /**
  71713. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  71714. */
  71715. set: function (time) {
  71716. this._elevationReturnWaitTime = time;
  71717. },
  71718. enumerable: true,
  71719. configurable: true
  71720. });
  71721. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  71722. /**
  71723. * Gets the flag that indicates if user zooming should stop animation.
  71724. */
  71725. get: function () {
  71726. return this._zoomStopsAnimation;
  71727. },
  71728. /**
  71729. * Sets the flag that indicates if user zooming should stop animation.
  71730. */
  71731. set: function (flag) {
  71732. this._zoomStopsAnimation = flag;
  71733. },
  71734. enumerable: true,
  71735. configurable: true
  71736. });
  71737. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  71738. /**
  71739. * Gets the transition time when framing the mesh, in milliseconds
  71740. */
  71741. get: function () {
  71742. return this._framingTime;
  71743. },
  71744. /**
  71745. * Sets the transition time when framing the mesh, in milliseconds
  71746. */
  71747. set: function (time) {
  71748. this._framingTime = time;
  71749. },
  71750. enumerable: true,
  71751. configurable: true
  71752. });
  71753. FramingBehavior.prototype.attach = function (camera) {
  71754. var _this = this;
  71755. this._attachedCamera = camera;
  71756. var scene = this._attachedCamera.getScene();
  71757. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  71758. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  71759. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71760. _this._isPointerDown = true;
  71761. return;
  71762. }
  71763. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  71764. _this._isPointerDown = false;
  71765. }
  71766. });
  71767. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  71768. if (mesh) {
  71769. _this.zoomOnMesh(mesh);
  71770. }
  71771. });
  71772. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  71773. // Stop the animation if there is user interaction and the animation should stop for this interaction
  71774. _this._applyUserInteraction();
  71775. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  71776. // back to the default position after a given timeout
  71777. _this._maintainCameraAboveGround();
  71778. });
  71779. };
  71780. FramingBehavior.prototype.detach = function () {
  71781. var scene = this._attachedCamera.getScene();
  71782. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  71783. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  71784. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  71785. this._attachedCamera = null;
  71786. };
  71787. /**
  71788. * Targets the given mesh and updates zoom level accordingly.
  71789. * @param mesh The mesh to target.
  71790. * @param radius Optional. If a cached radius position already exists, overrides default.
  71791. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  71792. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  71793. * @param onAnimationEnd Callback triggered at the end of the framing animation
  71794. */
  71795. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  71796. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  71797. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  71798. mesh.computeWorldMatrix(true);
  71799. var boundingBox = mesh.getBoundingInfo().boundingBox;
  71800. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  71801. };
  71802. /**
  71803. * Targets the given mesh and updates zoom level accordingly.
  71804. * @param mesh The mesh to target.
  71805. * @param radius Optional. If a cached radius position already exists, overrides default.
  71806. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  71807. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  71808. * @param onAnimationEnd Callback triggered at the end of the framing animation
  71809. */
  71810. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  71811. var _this = this;
  71812. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  71813. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  71814. var zoomTarget;
  71815. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  71816. var bottom = minimumWorld.y;
  71817. var top = maximumWorld.y;
  71818. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  71819. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  71820. if (focusOnOriginXZ) {
  71821. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  71822. }
  71823. else {
  71824. var centerWorld = minimumWorld.add(radiusWorld);
  71825. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  71826. }
  71827. if (!this._vectorTransition) {
  71828. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  71829. }
  71830. this._betaIsAnimating = true;
  71831. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  71832. // sets the radius and lower radius bounds
  71833. // Small delta ensures camera is not always at lower zoom limit.
  71834. var delta = 0.1;
  71835. var radius = 0;
  71836. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  71837. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  71838. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  71839. radius = position;
  71840. }
  71841. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  71842. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  71843. if (this._attachedCamera.lowerRadiusLimit === null) {
  71844. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  71845. }
  71846. }
  71847. // Set sensibilities
  71848. var extend = maximumWorld.subtract(minimumWorld).length();
  71849. this._attachedCamera.panningSensibility = 5000 / extend;
  71850. this._attachedCamera.wheelPrecision = 100 / radius;
  71851. // transition to new radius
  71852. if (!this._radiusTransition) {
  71853. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  71854. }
  71855. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  71856. if (onAnimationEnd) {
  71857. onAnimationEnd();
  71858. }
  71859. _this._attachedCamera.storeState();
  71860. }));
  71861. };
  71862. /**
  71863. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  71864. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  71865. * frustum width.
  71866. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  71867. * to fully enclose the mesh in the viewing frustum.
  71868. */
  71869. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  71870. var size = maximumWorld.subtract(minimumWorld);
  71871. var boxVectorGlobalDiagonal = size.length();
  71872. var frustumSlope = this._getFrustumSlope();
  71873. // Formula for setting distance
  71874. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  71875. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  71876. // Horizon distance
  71877. var radius = radiusWithoutFraming * this._radiusScale;
  71878. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  71879. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  71880. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  71881. var camera = this._attachedCamera;
  71882. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  71883. // Don't exceed the requested limit
  71884. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  71885. }
  71886. // Don't exceed the upper radius limit
  71887. if (camera.upperRadiusLimit) {
  71888. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  71889. }
  71890. return distance;
  71891. };
  71892. /**
  71893. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  71894. * is automatically returned to its default position (expected to be above ground plane).
  71895. */
  71896. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  71897. var _this = this;
  71898. if (this._elevationReturnTime < 0) {
  71899. return;
  71900. }
  71901. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  71902. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  71903. var limitBeta = Math.PI * 0.5;
  71904. // Bring the camera back up if below the ground plane
  71905. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  71906. this._betaIsAnimating = true;
  71907. //Transition to new position
  71908. this.stopAllAnimations();
  71909. if (!this._betaTransition) {
  71910. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  71911. }
  71912. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  71913. _this._clearAnimationLocks();
  71914. _this.stopAllAnimations();
  71915. }));
  71916. }
  71917. };
  71918. /**
  71919. * Returns the frustum slope based on the canvas ratio and camera FOV
  71920. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  71921. */
  71922. FramingBehavior.prototype._getFrustumSlope = function () {
  71923. // Calculate the viewport ratio
  71924. // Aspect Ratio is Height/Width.
  71925. var camera = this._attachedCamera;
  71926. var engine = camera.getScene().getEngine();
  71927. var aspectRatio = engine.getAspectRatio(camera);
  71928. // Camera FOV is the vertical field of view (top-bottom) in radians.
  71929. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  71930. var frustumSlopeY = Math.tan(camera.fov / 2);
  71931. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  71932. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  71933. // along the forward vector.
  71934. var frustumSlopeX = frustumSlopeY * aspectRatio;
  71935. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  71936. };
  71937. /**
  71938. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  71939. */
  71940. FramingBehavior.prototype._clearAnimationLocks = function () {
  71941. this._betaIsAnimating = false;
  71942. };
  71943. /**
  71944. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  71945. */
  71946. FramingBehavior.prototype._applyUserInteraction = function () {
  71947. if (this.isUserIsMoving) {
  71948. this._lastInteractionTime = BABYLON.Tools.Now;
  71949. this.stopAllAnimations();
  71950. this._clearAnimationLocks();
  71951. }
  71952. };
  71953. /**
  71954. * Stops and removes all animations that have been applied to the camera
  71955. */
  71956. FramingBehavior.prototype.stopAllAnimations = function () {
  71957. this._attachedCamera.animations = [];
  71958. while (this._animatables.length) {
  71959. if (this._animatables[0]) {
  71960. this._animatables[0].onAnimationEnd = null;
  71961. this._animatables[0].stop();
  71962. }
  71963. this._animatables.shift();
  71964. }
  71965. };
  71966. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  71967. /**
  71968. * Gets a value indicating if the user is moving the camera
  71969. */
  71970. get: function () {
  71971. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  71972. this._attachedCamera.inertialBetaOffset !== 0 ||
  71973. this._attachedCamera.inertialRadiusOffset !== 0 ||
  71974. this._attachedCamera.inertialPanningX !== 0 ||
  71975. this._attachedCamera.inertialPanningY !== 0 ||
  71976. this._isPointerDown;
  71977. },
  71978. enumerable: true,
  71979. configurable: true
  71980. });
  71981. return FramingBehavior;
  71982. }());
  71983. /**
  71984. * The easing function used by animations
  71985. */
  71986. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  71987. /**
  71988. * The easing mode used by animations
  71989. */
  71990. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  71991. // Statics
  71992. /**
  71993. * The camera can move all the way towards the mesh.
  71994. */
  71995. FramingBehavior.IgnoreBoundsSizeMode = 0;
  71996. /**
  71997. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  71998. */
  71999. FramingBehavior.FitFrustumSidesMode = 1;
  72000. BABYLON.FramingBehavior = FramingBehavior;
  72001. })(BABYLON || (BABYLON = {}));
  72002. //# sourceMappingURL=babylon.framingBehavior.js.map
  72003. var BABYLON;
  72004. (function (BABYLON) {
  72005. /**
  72006. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  72007. */
  72008. var BouncingBehavior = (function () {
  72009. function BouncingBehavior() {
  72010. /**
  72011. * The duration of the animation, in milliseconds
  72012. */
  72013. this.transitionDuration = 450;
  72014. /**
  72015. * Length of the distance animated by the transition when lower radius is reached
  72016. */
  72017. this.lowerRadiusTransitionRange = 2;
  72018. /**
  72019. * Length of the distance animated by the transition when upper radius is reached
  72020. */
  72021. this.upperRadiusTransitionRange = -2;
  72022. this._autoTransitionRange = false;
  72023. // Animations
  72024. this._radiusIsAnimating = false;
  72025. this._radiusBounceTransition = null;
  72026. this._animatables = new Array();
  72027. }
  72028. Object.defineProperty(BouncingBehavior.prototype, "name", {
  72029. get: function () {
  72030. return "Bouncing";
  72031. },
  72032. enumerable: true,
  72033. configurable: true
  72034. });
  72035. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  72036. /**
  72037. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  72038. */
  72039. get: function () {
  72040. return this._autoTransitionRange;
  72041. },
  72042. /**
  72043. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  72044. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  72045. */
  72046. set: function (value) {
  72047. var _this = this;
  72048. if (this._autoTransitionRange === value) {
  72049. return;
  72050. }
  72051. this._autoTransitionRange = value;
  72052. var camera = this._attachedCamera;
  72053. if (value) {
  72054. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  72055. if (!mesh) {
  72056. return;
  72057. }
  72058. mesh.computeWorldMatrix(true);
  72059. var diagonal = mesh.getBoundingInfo().diagonalLength;
  72060. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  72061. _this.upperRadiusTransitionRange = diagonal * 0.05;
  72062. });
  72063. }
  72064. else if (this._onMeshTargetChangedObserver) {
  72065. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72066. }
  72067. },
  72068. enumerable: true,
  72069. configurable: true
  72070. });
  72071. BouncingBehavior.prototype.attach = function (camera) {
  72072. var _this = this;
  72073. this._attachedCamera = camera;
  72074. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  72075. // Add the bounce animation to the lower radius limit
  72076. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  72077. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  72078. }
  72079. // Add the bounce animation to the upper radius limit
  72080. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  72081. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  72082. }
  72083. });
  72084. };
  72085. BouncingBehavior.prototype.detach = function () {
  72086. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  72087. if (this._onMeshTargetChangedObserver) {
  72088. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72089. }
  72090. this._attachedCamera = null;
  72091. };
  72092. /**
  72093. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  72094. * @param radiusLimit The limit to check against.
  72095. * @return Bool to indicate if at limit.
  72096. */
  72097. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  72098. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  72099. return true;
  72100. }
  72101. return false;
  72102. };
  72103. /**
  72104. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  72105. * @param radiusDelta The delta by which to animate to. Can be negative.
  72106. */
  72107. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  72108. var _this = this;
  72109. if (!this._radiusBounceTransition) {
  72110. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  72111. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  72112. }
  72113. // Prevent zoom until bounce has completed
  72114. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  72115. this._attachedCamera.wheelPrecision = Infinity;
  72116. this._attachedCamera.inertialRadiusOffset = 0;
  72117. // Animate to the radius limit
  72118. this.stopAllAnimations();
  72119. this._radiusIsAnimating = true;
  72120. 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(); }));
  72121. };
  72122. /**
  72123. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  72124. */
  72125. BouncingBehavior.prototype._clearAnimationLocks = function () {
  72126. this._radiusIsAnimating = false;
  72127. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  72128. };
  72129. /**
  72130. * Stops and removes all animations that have been applied to the camera
  72131. */
  72132. BouncingBehavior.prototype.stopAllAnimations = function () {
  72133. this._attachedCamera.animations = [];
  72134. while (this._animatables.length) {
  72135. this._animatables[0].onAnimationEnd = null;
  72136. this._animatables[0].stop();
  72137. this._animatables.shift();
  72138. }
  72139. };
  72140. return BouncingBehavior;
  72141. }());
  72142. /**
  72143. * The easing function used by animations
  72144. */
  72145. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  72146. /**
  72147. * The easing mode used by animations
  72148. */
  72149. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  72150. BABYLON.BouncingBehavior = BouncingBehavior;
  72151. })(BABYLON || (BABYLON = {}));
  72152. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  72153. var BABYLON;
  72154. (function (BABYLON) {
  72155. var AutoRotationBehavior = (function () {
  72156. function AutoRotationBehavior() {
  72157. this._zoomStopsAnimation = false;
  72158. this._idleRotationSpeed = 0.05;
  72159. this._idleRotationWaitTime = 2000;
  72160. this._idleRotationSpinupTime = 2000;
  72161. this._isPointerDown = false;
  72162. this._lastFrameTime = null;
  72163. this._lastInteractionTime = -Infinity;
  72164. this._cameraRotationSpeed = 0;
  72165. this._lastFrameRadius = 0;
  72166. }
  72167. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  72168. get: function () {
  72169. return "AutoRotation";
  72170. },
  72171. enumerable: true,
  72172. configurable: true
  72173. });
  72174. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  72175. /**
  72176. * Gets the flag that indicates if user zooming should stop animation.
  72177. */
  72178. get: function () {
  72179. return this._zoomStopsAnimation;
  72180. },
  72181. /**
  72182. * Sets the flag that indicates if user zooming should stop animation.
  72183. */
  72184. set: function (flag) {
  72185. this._zoomStopsAnimation = flag;
  72186. },
  72187. enumerable: true,
  72188. configurable: true
  72189. });
  72190. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  72191. /**
  72192. * Gets the default speed at which the camera rotates around the model.
  72193. */
  72194. get: function () {
  72195. return this._idleRotationSpeed;
  72196. },
  72197. /**
  72198. * Sets the default speed at which the camera rotates around the model.
  72199. */
  72200. set: function (speed) {
  72201. this._idleRotationSpeed = speed;
  72202. },
  72203. enumerable: true,
  72204. configurable: true
  72205. });
  72206. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  72207. /**
  72208. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  72209. */
  72210. get: function () {
  72211. return this._idleRotationWaitTime;
  72212. },
  72213. /**
  72214. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  72215. */
  72216. set: function (time) {
  72217. this._idleRotationWaitTime = time;
  72218. },
  72219. enumerable: true,
  72220. configurable: true
  72221. });
  72222. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  72223. /**
  72224. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  72225. */
  72226. get: function () {
  72227. return this._idleRotationSpinupTime;
  72228. },
  72229. /**
  72230. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  72231. */
  72232. set: function (time) {
  72233. this._idleRotationSpinupTime = time;
  72234. },
  72235. enumerable: true,
  72236. configurable: true
  72237. });
  72238. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  72239. /**
  72240. * Gets a value indicating if the camera is currently rotating because of this behavior
  72241. */
  72242. get: function () {
  72243. return Math.abs(this._cameraRotationSpeed) > 0;
  72244. },
  72245. enumerable: true,
  72246. configurable: true
  72247. });
  72248. AutoRotationBehavior.prototype.attach = function (camera) {
  72249. var _this = this;
  72250. this._attachedCamera = camera;
  72251. var scene = this._attachedCamera.getScene();
  72252. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  72253. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72254. _this._isPointerDown = true;
  72255. return;
  72256. }
  72257. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  72258. _this._isPointerDown = false;
  72259. }
  72260. });
  72261. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  72262. var now = BABYLON.Tools.Now;
  72263. var dt = 0;
  72264. if (_this._lastFrameTime != null) {
  72265. dt = now - _this._lastFrameTime;
  72266. }
  72267. _this._lastFrameTime = now;
  72268. // Stop the animation if there is user interaction and the animation should stop for this interaction
  72269. _this._applyUserInteraction();
  72270. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  72271. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  72272. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  72273. // Step camera rotation by rotation speed
  72274. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  72275. });
  72276. };
  72277. AutoRotationBehavior.prototype.detach = function () {
  72278. var scene = this._attachedCamera.getScene();
  72279. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  72280. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  72281. this._attachedCamera = null;
  72282. };
  72283. /**
  72284. * Returns true if user is scrolling.
  72285. * @return true if user is scrolling.
  72286. */
  72287. AutoRotationBehavior.prototype._userIsZooming = function () {
  72288. return this._attachedCamera.inertialRadiusOffset !== 0;
  72289. };
  72290. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  72291. var zoomHasHitLimit = false;
  72292. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  72293. zoomHasHitLimit = true;
  72294. }
  72295. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  72296. this._lastFrameRadius = this._attachedCamera.radius;
  72297. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  72298. };
  72299. /**
  72300. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  72301. */
  72302. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  72303. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  72304. this._lastInteractionTime = BABYLON.Tools.Now;
  72305. }
  72306. };
  72307. // Tools
  72308. AutoRotationBehavior.prototype._userIsMoving = function () {
  72309. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  72310. this._attachedCamera.inertialBetaOffset !== 0 ||
  72311. this._attachedCamera.inertialRadiusOffset !== 0 ||
  72312. this._attachedCamera.inertialPanningX !== 0 ||
  72313. this._attachedCamera.inertialPanningY !== 0 ||
  72314. this._isPointerDown;
  72315. };
  72316. return AutoRotationBehavior;
  72317. }());
  72318. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  72319. })(BABYLON || (BABYLON = {}));
  72320. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  72321. 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}"};
  72322. 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};"};
  72323. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  72324. var BABYLON;
  72325. (function (BABYLON) {
  72326. var GridMaterialDefines = (function (_super) {
  72327. __extends(GridMaterialDefines, _super);
  72328. function GridMaterialDefines() {
  72329. var _this = _super.call(this) || this;
  72330. _this.TRANSPARENT = false;
  72331. _this.FOG = false;
  72332. _this.PREMULTIPLYALPHA = false;
  72333. _this.rebuild();
  72334. return _this;
  72335. }
  72336. return GridMaterialDefines;
  72337. }(BABYLON.MaterialDefines));
  72338. /**
  72339. * The grid materials allows you to wrap any shape with a grid.
  72340. * Colors are customizable.
  72341. */
  72342. var GridMaterial = (function (_super) {
  72343. __extends(GridMaterial, _super);
  72344. /**
  72345. * constructor
  72346. * @param name The name given to the material in order to identify it afterwards.
  72347. * @param scene The scene the material is used in.
  72348. */
  72349. function GridMaterial(name, scene) {
  72350. var _this = _super.call(this, name, scene) || this;
  72351. /**
  72352. * Main color of the grid (e.g. between lines)
  72353. */
  72354. _this.mainColor = BABYLON.Color3.Black();
  72355. /**
  72356. * Color of the grid lines.
  72357. */
  72358. _this.lineColor = BABYLON.Color3.Teal();
  72359. /**
  72360. * The scale of the grid compared to unit.
  72361. */
  72362. _this.gridRatio = 1.0;
  72363. /**
  72364. * Allows setting an offset for the grid lines.
  72365. */
  72366. _this.gridOffset = BABYLON.Vector3.Zero();
  72367. /**
  72368. * The frequency of thicker lines.
  72369. */
  72370. _this.majorUnitFrequency = 10;
  72371. /**
  72372. * The visibility of minor units in the grid.
  72373. */
  72374. _this.minorUnitVisibility = 0.33;
  72375. /**
  72376. * The grid opacity outside of the lines.
  72377. */
  72378. _this.opacity = 1.0;
  72379. /**
  72380. * Determine RBG output is premultiplied by alpha value.
  72381. */
  72382. _this.preMultiplyAlpha = false;
  72383. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  72384. return _this;
  72385. }
  72386. /**
  72387. * Returns wehter or not the grid requires alpha blending.
  72388. */
  72389. GridMaterial.prototype.needAlphaBlending = function () {
  72390. return this.opacity < 1.0;
  72391. };
  72392. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  72393. if (this.isFrozen) {
  72394. if (this._wasPreviouslyReady && subMesh.effect) {
  72395. return true;
  72396. }
  72397. }
  72398. if (!subMesh._materialDefines) {
  72399. subMesh._materialDefines = new GridMaterialDefines();
  72400. }
  72401. var defines = subMesh._materialDefines;
  72402. var scene = this.getScene();
  72403. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  72404. if (this._renderId === scene.getRenderId()) {
  72405. return true;
  72406. }
  72407. }
  72408. var engine = scene.getEngine();
  72409. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  72410. defines.TRANSPARENT = !defines.TRANSPARENT;
  72411. defines.markAsUnprocessed();
  72412. }
  72413. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  72414. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  72415. defines.markAsUnprocessed();
  72416. }
  72417. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  72418. // Get correct effect
  72419. if (defines.isDirty) {
  72420. defines.markAsProcessed();
  72421. scene.resetCachedMaterial();
  72422. // Attributes
  72423. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  72424. // Defines
  72425. var join = defines.toString();
  72426. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  72427. }
  72428. if (!subMesh.effect.isReady()) {
  72429. return false;
  72430. }
  72431. this._renderId = scene.getRenderId();
  72432. this._wasPreviouslyReady = true;
  72433. return true;
  72434. };
  72435. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  72436. var scene = this.getScene();
  72437. var defines = subMesh._materialDefines;
  72438. if (!defines) {
  72439. return;
  72440. }
  72441. var effect = subMesh.effect;
  72442. this._activeEffect = effect;
  72443. // Matrices
  72444. this.bindOnlyWorldMatrix(world);
  72445. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  72446. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  72447. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  72448. // Uniforms
  72449. if (this._mustRebind(scene, effect)) {
  72450. this._activeEffect.setColor3("mainColor", this.mainColor);
  72451. this._activeEffect.setColor3("lineColor", this.lineColor);
  72452. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  72453. this._gridControl.x = this.gridRatio;
  72454. this._gridControl.y = Math.round(this.majorUnitFrequency);
  72455. this._gridControl.z = this.minorUnitVisibility;
  72456. this._gridControl.w = this.opacity;
  72457. this._activeEffect.setVector4("gridControl", this._gridControl);
  72458. }
  72459. // Fog
  72460. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  72461. this._afterBind(mesh, this._activeEffect);
  72462. };
  72463. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  72464. _super.prototype.dispose.call(this, forceDisposeEffect);
  72465. };
  72466. GridMaterial.prototype.clone = function (name) {
  72467. var _this = this;
  72468. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  72469. };
  72470. GridMaterial.prototype.serialize = function () {
  72471. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  72472. serializationObject.customType = "BABYLON.GridMaterial";
  72473. return serializationObject;
  72474. };
  72475. GridMaterial.prototype.getClassName = function () {
  72476. return "GridMaterial";
  72477. };
  72478. GridMaterial.Parse = function (source, scene, rootUrl) {
  72479. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  72480. };
  72481. return GridMaterial;
  72482. }(BABYLON.PushMaterial));
  72483. __decorate([
  72484. BABYLON.serializeAsColor3()
  72485. ], GridMaterial.prototype, "mainColor", void 0);
  72486. __decorate([
  72487. BABYLON.serializeAsColor3()
  72488. ], GridMaterial.prototype, "lineColor", void 0);
  72489. __decorate([
  72490. BABYLON.serialize()
  72491. ], GridMaterial.prototype, "gridRatio", void 0);
  72492. __decorate([
  72493. BABYLON.serializeAsColor3()
  72494. ], GridMaterial.prototype, "gridOffset", void 0);
  72495. __decorate([
  72496. BABYLON.serialize()
  72497. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  72498. __decorate([
  72499. BABYLON.serialize()
  72500. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  72501. __decorate([
  72502. BABYLON.serialize()
  72503. ], GridMaterial.prototype, "opacity", void 0);
  72504. __decorate([
  72505. BABYLON.serialize()
  72506. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  72507. BABYLON.GridMaterial = GridMaterial;
  72508. })(BABYLON || (BABYLON = {}));
  72509. //# sourceMappingURL=babylon.gridmaterial.js.map
  72510. 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}";
  72511. 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}";
  72512. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  72513. var BABYLON;
  72514. (function (BABYLON) {
  72515. var GLTFLoaderCoordinateSystemMode;
  72516. (function (GLTFLoaderCoordinateSystemMode) {
  72517. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  72518. // 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.
  72519. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  72520. // The glTF right-handed data is not transformed in any form and is loaded directly.
  72521. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  72522. // Sets the useRightHandedSystem flag on the scene.
  72523. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  72524. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  72525. var GLTFFileLoader = (function () {
  72526. function GLTFFileLoader() {
  72527. // V2 options
  72528. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  72529. this.name = "gltf";
  72530. this.extensions = {
  72531. ".gltf": { isBinary: false },
  72532. ".glb": { isBinary: true }
  72533. };
  72534. }
  72535. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  72536. var loaderData = GLTFFileLoader._parse(data, onError);
  72537. if (!loaderData) {
  72538. return;
  72539. }
  72540. if (this.onParsed) {
  72541. this.onParsed(loaderData);
  72542. }
  72543. var loader = this._getLoader(loaderData, onError);
  72544. if (!loader) {
  72545. return;
  72546. }
  72547. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  72548. };
  72549. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  72550. var loaderData = GLTFFileLoader._parse(data, onError);
  72551. if (!loaderData) {
  72552. return;
  72553. }
  72554. if (this.onParsed) {
  72555. this.onParsed(loaderData);
  72556. }
  72557. var loader = this._getLoader(loaderData, onError);
  72558. if (!loader) {
  72559. return;
  72560. }
  72561. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  72562. };
  72563. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  72564. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  72565. };
  72566. GLTFFileLoader._parse = function (data, onError) {
  72567. try {
  72568. if (data instanceof ArrayBuffer) {
  72569. return GLTFFileLoader._parseBinary(data, onError);
  72570. }
  72571. return {
  72572. json: JSON.parse(data),
  72573. bin: null
  72574. };
  72575. }
  72576. catch (e) {
  72577. onError(e.message);
  72578. return null;
  72579. }
  72580. };
  72581. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  72582. var loaderVersion = { major: 2, minor: 0 };
  72583. var asset = loaderData.json.asset || {};
  72584. var version = GLTFFileLoader._parseVersion(asset.version);
  72585. if (!version) {
  72586. onError("Invalid version: " + asset.version);
  72587. return null;
  72588. }
  72589. if (asset.minVersion !== undefined) {
  72590. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  72591. if (!minVersion) {
  72592. onError("Invalid minimum version: " + asset.minVersion);
  72593. return null;
  72594. }
  72595. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  72596. onError("Incompatible minimum version: " + asset.minVersion);
  72597. return null;
  72598. }
  72599. }
  72600. var createLoaders = {
  72601. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  72602. 2: GLTFFileLoader.CreateGLTFLoaderV2
  72603. };
  72604. var createLoader = createLoaders[version.major];
  72605. if (!createLoader) {
  72606. onError("Unsupported version: " + asset.version);
  72607. return null;
  72608. }
  72609. return createLoader(this);
  72610. };
  72611. GLTFFileLoader._parseBinary = function (data, onError) {
  72612. var Binary = {
  72613. Magic: 0x46546C67
  72614. };
  72615. var binaryReader = new BinaryReader(data);
  72616. var magic = binaryReader.readUint32();
  72617. if (magic !== Binary.Magic) {
  72618. onError("Unexpected magic: " + magic);
  72619. return null;
  72620. }
  72621. var version = binaryReader.readUint32();
  72622. switch (version) {
  72623. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  72624. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  72625. }
  72626. onError("Unsupported version: " + version);
  72627. return null;
  72628. };
  72629. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  72630. var ContentFormat = {
  72631. JSON: 0
  72632. };
  72633. var length = binaryReader.readUint32();
  72634. if (length != binaryReader.getLength()) {
  72635. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  72636. return null;
  72637. }
  72638. var contentLength = binaryReader.readUint32();
  72639. var contentFormat = binaryReader.readUint32();
  72640. var content;
  72641. switch (contentFormat) {
  72642. case ContentFormat.JSON:
  72643. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  72644. break;
  72645. default:
  72646. onError("Unexpected content format: " + contentFormat);
  72647. return null;
  72648. }
  72649. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  72650. var body = binaryReader.readUint8Array(bytesRemaining);
  72651. return {
  72652. json: content,
  72653. bin: body
  72654. };
  72655. };
  72656. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  72657. var ChunkFormat = {
  72658. JSON: 0x4E4F534A,
  72659. BIN: 0x004E4942
  72660. };
  72661. var length = binaryReader.readUint32();
  72662. if (length !== binaryReader.getLength()) {
  72663. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  72664. return null;
  72665. }
  72666. // JSON chunk
  72667. var chunkLength = binaryReader.readUint32();
  72668. var chunkFormat = binaryReader.readUint32();
  72669. if (chunkFormat !== ChunkFormat.JSON) {
  72670. onError("First chunk format is not JSON");
  72671. return null;
  72672. }
  72673. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  72674. // Look for BIN chunk
  72675. var bin = null;
  72676. while (binaryReader.getPosition() < binaryReader.getLength()) {
  72677. chunkLength = binaryReader.readUint32();
  72678. chunkFormat = binaryReader.readUint32();
  72679. switch (chunkFormat) {
  72680. case ChunkFormat.JSON:
  72681. onError("Unexpected JSON chunk");
  72682. return null;
  72683. case ChunkFormat.BIN:
  72684. bin = binaryReader.readUint8Array(chunkLength);
  72685. break;
  72686. default:
  72687. // ignore unrecognized chunkFormat
  72688. binaryReader.skipBytes(chunkLength);
  72689. break;
  72690. }
  72691. }
  72692. return {
  72693. json: json,
  72694. bin: bin
  72695. };
  72696. };
  72697. GLTFFileLoader._parseVersion = function (version) {
  72698. if (!version) {
  72699. return null;
  72700. }
  72701. var parts = version.split(".");
  72702. if (parts.length != 2) {
  72703. return null;
  72704. }
  72705. var major = +parts[0];
  72706. if (isNaN(major)) {
  72707. return null;
  72708. }
  72709. var minor = +parts[1];
  72710. if (isNaN(minor)) {
  72711. return null;
  72712. }
  72713. return {
  72714. major: major,
  72715. minor: minor
  72716. };
  72717. };
  72718. GLTFFileLoader._compareVersion = function (a, b) {
  72719. if (a.major > b.major)
  72720. return 1;
  72721. if (a.major < b.major)
  72722. return -1;
  72723. if (a.minor > b.minor)
  72724. return 1;
  72725. if (a.minor < b.minor)
  72726. return -1;
  72727. return 0;
  72728. };
  72729. GLTFFileLoader._decodeBufferToText = function (view) {
  72730. var result = "";
  72731. var length = view.byteLength;
  72732. for (var i = 0; i < length; ++i) {
  72733. result += String.fromCharCode(view[i]);
  72734. }
  72735. return result;
  72736. };
  72737. return GLTFFileLoader;
  72738. }());
  72739. // V1 options
  72740. GLTFFileLoader.HomogeneousCoordinates = false;
  72741. GLTFFileLoader.IncrementalLoading = true;
  72742. BABYLON.GLTFFileLoader = GLTFFileLoader;
  72743. var BinaryReader = (function () {
  72744. function BinaryReader(arrayBuffer) {
  72745. this._arrayBuffer = arrayBuffer;
  72746. this._dataView = new DataView(arrayBuffer);
  72747. this._byteOffset = 0;
  72748. }
  72749. BinaryReader.prototype.getPosition = function () {
  72750. return this._byteOffset;
  72751. };
  72752. BinaryReader.prototype.getLength = function () {
  72753. return this._arrayBuffer.byteLength;
  72754. };
  72755. BinaryReader.prototype.readUint32 = function () {
  72756. var value = this._dataView.getUint32(this._byteOffset, true);
  72757. this._byteOffset += 4;
  72758. return value;
  72759. };
  72760. BinaryReader.prototype.readUint8Array = function (length) {
  72761. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  72762. this._byteOffset += length;
  72763. return value;
  72764. };
  72765. BinaryReader.prototype.skipBytes = function (length) {
  72766. this._byteOffset += length;
  72767. };
  72768. return BinaryReader;
  72769. }());
  72770. if (BABYLON.SceneLoader) {
  72771. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  72772. }
  72773. })(BABYLON || (BABYLON = {}));
  72774. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  72775. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  72776. var BABYLON;
  72777. (function (BABYLON) {
  72778. var GLTF1;
  72779. (function (GLTF1) {
  72780. /**
  72781. * Enums
  72782. */
  72783. var EComponentType;
  72784. (function (EComponentType) {
  72785. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  72786. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  72787. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  72788. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  72789. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  72790. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  72791. var EShaderType;
  72792. (function (EShaderType) {
  72793. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  72794. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  72795. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  72796. var EParameterType;
  72797. (function (EParameterType) {
  72798. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  72799. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  72800. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  72801. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  72802. EParameterType[EParameterType["INT"] = 5124] = "INT";
  72803. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  72804. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  72805. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  72806. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  72807. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  72808. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  72809. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  72810. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  72811. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  72812. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  72813. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  72814. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  72815. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  72816. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  72817. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  72818. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  72819. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  72820. var ETextureWrapMode;
  72821. (function (ETextureWrapMode) {
  72822. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  72823. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  72824. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  72825. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  72826. var ETextureFilterType;
  72827. (function (ETextureFilterType) {
  72828. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  72829. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  72830. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  72831. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  72832. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  72833. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  72834. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  72835. var ETextureFormat;
  72836. (function (ETextureFormat) {
  72837. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  72838. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  72839. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  72840. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  72841. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  72842. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  72843. var ECullingType;
  72844. (function (ECullingType) {
  72845. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  72846. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  72847. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  72848. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  72849. var EBlendingFunction;
  72850. (function (EBlendingFunction) {
  72851. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  72852. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  72853. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  72854. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  72855. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  72856. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  72857. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  72858. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  72859. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  72860. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  72861. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  72862. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  72863. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  72864. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  72865. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  72866. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  72867. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  72868. })(BABYLON || (BABYLON = {}));
  72869. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  72870. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  72871. var BABYLON;
  72872. (function (BABYLON) {
  72873. var GLTF1;
  72874. (function (GLTF1) {
  72875. /**
  72876. * Tokenizer. Used for shaders compatibility
  72877. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  72878. */
  72879. var ETokenType;
  72880. (function (ETokenType) {
  72881. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  72882. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  72883. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  72884. })(ETokenType || (ETokenType = {}));
  72885. var Tokenizer = (function () {
  72886. function Tokenizer(toParse) {
  72887. this._pos = 0;
  72888. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  72889. this._toParse = toParse;
  72890. this._maxPos = toParse.length;
  72891. }
  72892. Tokenizer.prototype.getNextToken = function () {
  72893. if (this.isEnd())
  72894. return ETokenType.END_OF_INPUT;
  72895. this.currentString = this.read();
  72896. this.currentToken = ETokenType.UNKNOWN;
  72897. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  72898. this.currentToken = ETokenType.IDENTIFIER;
  72899. this.currentIdentifier = this.currentString;
  72900. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  72901. this.currentIdentifier += this.currentString;
  72902. this.forward();
  72903. }
  72904. }
  72905. return this.currentToken;
  72906. };
  72907. Tokenizer.prototype.peek = function () {
  72908. return this._toParse[this._pos];
  72909. };
  72910. Tokenizer.prototype.read = function () {
  72911. return this._toParse[this._pos++];
  72912. };
  72913. Tokenizer.prototype.forward = function () {
  72914. this._pos++;
  72915. };
  72916. Tokenizer.prototype.isEnd = function () {
  72917. return this._pos >= this._maxPos;
  72918. };
  72919. return Tokenizer;
  72920. }());
  72921. /**
  72922. * Values
  72923. */
  72924. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  72925. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  72926. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  72927. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  72928. /**
  72929. * Parse
  72930. */
  72931. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  72932. for (var buf in parsedBuffers) {
  72933. var parsedBuffer = parsedBuffers[buf];
  72934. gltfRuntime.buffers[buf] = parsedBuffer;
  72935. gltfRuntime.buffersCount++;
  72936. }
  72937. };
  72938. var parseShaders = function (parsedShaders, gltfRuntime) {
  72939. for (var sha in parsedShaders) {
  72940. var parsedShader = parsedShaders[sha];
  72941. gltfRuntime.shaders[sha] = parsedShader;
  72942. gltfRuntime.shaderscount++;
  72943. }
  72944. };
  72945. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  72946. for (var object in parsedObjects) {
  72947. var parsedObject = parsedObjects[object];
  72948. gltfRuntime[runtimeProperty][object] = parsedObject;
  72949. }
  72950. };
  72951. /**
  72952. * Utils
  72953. */
  72954. var normalizeUVs = function (buffer) {
  72955. if (!buffer) {
  72956. return;
  72957. }
  72958. for (var i = 0; i < buffer.length / 2; i++) {
  72959. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  72960. }
  72961. };
  72962. var replaceInString = function (str, searchValue, replaceValue) {
  72963. while (str.indexOf(searchValue) !== -1) {
  72964. str = str.replace(searchValue, replaceValue);
  72965. }
  72966. return str;
  72967. };
  72968. var getAttribute = function (attributeParameter) {
  72969. if (attributeParameter.semantic === "NORMAL") {
  72970. return "normal";
  72971. }
  72972. else if (attributeParameter.semantic === "POSITION") {
  72973. return "position";
  72974. }
  72975. else if (attributeParameter.semantic === "JOINT") {
  72976. return "matricesIndices";
  72977. }
  72978. else if (attributeParameter.semantic === "WEIGHT") {
  72979. return "matricesWeights";
  72980. }
  72981. else if (attributeParameter.semantic === "COLOR") {
  72982. return "color";
  72983. }
  72984. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  72985. var channel = Number(attributeParameter.semantic.split("_")[1]);
  72986. return "uv" + (channel === 0 ? "" : channel + 1);
  72987. }
  72988. };
  72989. /**
  72990. * Returns the animation path (glTF -> Babylon)
  72991. */
  72992. var getAnimationPath = function (path) {
  72993. var index = glTFAnimationPaths.indexOf(path);
  72994. if (index !== -1) {
  72995. return babylonAnimationPaths[index];
  72996. }
  72997. return path;
  72998. };
  72999. /**
  73000. * Loads and creates animations
  73001. */
  73002. var loadAnimations = function (gltfRuntime) {
  73003. for (var anim in gltfRuntime.animations) {
  73004. var animation = gltfRuntime.animations[anim];
  73005. var lastAnimation = null;
  73006. for (var i = 0; i < animation.channels.length; i++) {
  73007. // Get parameters and load buffers
  73008. var channel = animation.channels[i];
  73009. var sampler = animation.samplers[channel.sampler];
  73010. if (!sampler) {
  73011. continue;
  73012. }
  73013. var inputData = null;
  73014. var outputData = null;
  73015. if (animation.parameters) {
  73016. inputData = animation.parameters[sampler.input];
  73017. outputData = animation.parameters[sampler.output];
  73018. }
  73019. else {
  73020. inputData = sampler.input;
  73021. outputData = sampler.output;
  73022. }
  73023. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  73024. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  73025. var targetID = channel.target.id;
  73026. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  73027. if (targetNode === null) {
  73028. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  73029. }
  73030. if (targetNode === null) {
  73031. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  73032. continue;
  73033. }
  73034. var isBone = targetNode instanceof BABYLON.Bone;
  73035. // Get target path (position, rotation or scaling)
  73036. var targetPath = channel.target.path;
  73037. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  73038. if (targetPathIndex !== -1) {
  73039. targetPath = babylonAnimationPaths[targetPathIndex];
  73040. }
  73041. // Determine animation type
  73042. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  73043. if (!isBone) {
  73044. if (targetPath === "rotationQuaternion") {
  73045. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  73046. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  73047. }
  73048. else {
  73049. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  73050. }
  73051. }
  73052. // Create animation and key frames
  73053. var babylonAnimation = null;
  73054. var keys = [];
  73055. var arrayOffset = 0;
  73056. var modifyKey = false;
  73057. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  73058. babylonAnimation = lastAnimation;
  73059. modifyKey = true;
  73060. }
  73061. if (!modifyKey) {
  73062. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  73063. }
  73064. // For each frame
  73065. for (var j = 0; j < bufferInput.length; j++) {
  73066. var value = null;
  73067. if (targetPath === "rotationQuaternion") {
  73068. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  73069. arrayOffset += 4;
  73070. }
  73071. else {
  73072. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  73073. arrayOffset += 3;
  73074. }
  73075. if (isBone) {
  73076. var bone = targetNode;
  73077. var translation = BABYLON.Vector3.Zero();
  73078. var rotationQuaternion = new BABYLON.Quaternion();
  73079. var scaling = BABYLON.Vector3.Zero();
  73080. // Warning on decompose
  73081. var mat = bone.getBaseMatrix();
  73082. if (modifyKey) {
  73083. mat = lastAnimation.getKeys()[j].value;
  73084. }
  73085. mat.decompose(scaling, rotationQuaternion, translation);
  73086. if (targetPath === "position") {
  73087. translation = value;
  73088. }
  73089. else if (targetPath === "rotationQuaternion") {
  73090. rotationQuaternion = value;
  73091. }
  73092. else {
  73093. scaling = value;
  73094. }
  73095. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  73096. }
  73097. if (!modifyKey) {
  73098. keys.push({
  73099. frame: bufferInput[j],
  73100. value: value
  73101. });
  73102. }
  73103. else {
  73104. lastAnimation.getKeys()[j].value = value;
  73105. }
  73106. }
  73107. // Finish
  73108. if (!modifyKey) {
  73109. babylonAnimation.setKeys(keys);
  73110. targetNode.animations.push(babylonAnimation);
  73111. }
  73112. lastAnimation = babylonAnimation;
  73113. gltfRuntime.scene.stopAnimation(targetNode);
  73114. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  73115. }
  73116. }
  73117. };
  73118. /**
  73119. * Returns the bones transformation matrix
  73120. */
  73121. var configureBoneTransformation = function (node) {
  73122. var mat = null;
  73123. if (node.translation || node.rotation || node.scale) {
  73124. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  73125. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  73126. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  73127. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  73128. }
  73129. else {
  73130. mat = BABYLON.Matrix.FromArray(node.matrix);
  73131. }
  73132. return mat;
  73133. };
  73134. /**
  73135. * Returns the parent bone
  73136. */
  73137. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  73138. // Try to find
  73139. for (var i = 0; i < newSkeleton.bones.length; i++) {
  73140. if (newSkeleton.bones[i].name === jointName) {
  73141. return newSkeleton.bones[i];
  73142. }
  73143. }
  73144. // Not found, search in gltf nodes
  73145. var nodes = gltfRuntime.nodes;
  73146. for (var nde in nodes) {
  73147. var node = nodes[nde];
  73148. if (!node.jointName) {
  73149. continue;
  73150. }
  73151. var children = node.children;
  73152. for (var i = 0; i < children.length; i++) {
  73153. var child = gltfRuntime.nodes[children[i]];
  73154. if (!child.jointName) {
  73155. continue;
  73156. }
  73157. if (child.jointName === jointName) {
  73158. var mat = configureBoneTransformation(node);
  73159. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  73160. bone.id = nde;
  73161. return bone;
  73162. }
  73163. }
  73164. }
  73165. return null;
  73166. };
  73167. /**
  73168. * Returns the appropriate root node
  73169. */
  73170. var getNodeToRoot = function (nodesToRoot, id) {
  73171. for (var i = 0; i < nodesToRoot.length; i++) {
  73172. var nodeToRoot = nodesToRoot[i];
  73173. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  73174. var child = nodeToRoot.node.children[j];
  73175. if (child === id) {
  73176. return nodeToRoot.bone;
  73177. }
  73178. }
  73179. }
  73180. return null;
  73181. };
  73182. /**
  73183. * Returns the node with the joint name
  73184. */
  73185. var getJointNode = function (gltfRuntime, jointName) {
  73186. var nodes = gltfRuntime.nodes;
  73187. var node = nodes[jointName];
  73188. if (node) {
  73189. return {
  73190. node: node,
  73191. id: jointName
  73192. };
  73193. }
  73194. for (var nde in nodes) {
  73195. node = nodes[nde];
  73196. if (node.jointName === jointName) {
  73197. return {
  73198. node: node,
  73199. id: nde
  73200. };
  73201. }
  73202. }
  73203. return null;
  73204. };
  73205. /**
  73206. * Checks if a nodes is in joints
  73207. */
  73208. var nodeIsInJoints = function (skins, id) {
  73209. for (var i = 0; i < skins.jointNames.length; i++) {
  73210. if (skins.jointNames[i] === id) {
  73211. return true;
  73212. }
  73213. }
  73214. return false;
  73215. };
  73216. /**
  73217. * Fills the nodes to root for bones and builds hierarchy
  73218. */
  73219. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  73220. // Creates nodes for root
  73221. for (var nde in gltfRuntime.nodes) {
  73222. var node = gltfRuntime.nodes[nde];
  73223. var id = nde;
  73224. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  73225. continue;
  73226. }
  73227. // Create node to root bone
  73228. var mat = configureBoneTransformation(node);
  73229. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  73230. bone.id = id;
  73231. nodesToRoot.push({ bone: bone, node: node, id: id });
  73232. }
  73233. // Parenting
  73234. for (var i = 0; i < nodesToRoot.length; i++) {
  73235. var nodeToRoot = nodesToRoot[i];
  73236. var children = nodeToRoot.node.children;
  73237. for (var j = 0; j < children.length; j++) {
  73238. var child = null;
  73239. for (var k = 0; k < nodesToRoot.length; k++) {
  73240. if (nodesToRoot[k].id === children[j]) {
  73241. child = nodesToRoot[k];
  73242. break;
  73243. }
  73244. }
  73245. if (child) {
  73246. child.bone._parent = nodeToRoot.bone;
  73247. nodeToRoot.bone.children.push(child.bone);
  73248. }
  73249. }
  73250. }
  73251. };
  73252. var printMat = function (m) {
  73253. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  73254. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  73255. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  73256. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  73257. };
  73258. /**
  73259. * Imports a skeleton
  73260. */
  73261. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  73262. if (!newSkeleton) {
  73263. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  73264. }
  73265. if (!skins.babylonSkeleton) {
  73266. return newSkeleton;
  73267. }
  73268. // Matrices
  73269. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  73270. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  73271. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  73272. // Find the root bones
  73273. var nodesToRoot = [];
  73274. var nodesToRootToAdd = [];
  73275. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  73276. newSkeleton.bones = [];
  73277. // Joints
  73278. for (var i = 0; i < skins.jointNames.length; i++) {
  73279. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  73280. var node = jointNode.node;
  73281. if (!node) {
  73282. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  73283. continue;
  73284. }
  73285. var id = jointNode.id;
  73286. // Optimize, if the bone already exists...
  73287. var existingBone = gltfRuntime.scene.getBoneByID(id);
  73288. if (existingBone) {
  73289. newSkeleton.bones.push(existingBone);
  73290. continue;
  73291. }
  73292. // Search for parent bone
  73293. var foundBone = false;
  73294. var parentBone = null;
  73295. for (var j = 0; j < i; j++) {
  73296. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  73297. if (!joint) {
  73298. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  73299. continue;
  73300. }
  73301. var children = joint.children;
  73302. if (!children) {
  73303. continue;
  73304. }
  73305. foundBone = false;
  73306. for (var k = 0; k < children.length; k++) {
  73307. if (children[k] === id) {
  73308. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  73309. foundBone = true;
  73310. break;
  73311. }
  73312. }
  73313. if (foundBone) {
  73314. break;
  73315. }
  73316. }
  73317. // Create bone
  73318. var mat = configureBoneTransformation(node);
  73319. if (!parentBone && nodesToRoot.length > 0) {
  73320. parentBone = getNodeToRoot(nodesToRoot, id);
  73321. if (parentBone) {
  73322. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  73323. nodesToRootToAdd.push(parentBone);
  73324. }
  73325. }
  73326. }
  73327. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  73328. bone.id = id;
  73329. }
  73330. // Polish
  73331. var bones = newSkeleton.bones;
  73332. newSkeleton.bones = [];
  73333. for (var i = 0; i < skins.jointNames.length; i++) {
  73334. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  73335. if (!jointNode) {
  73336. continue;
  73337. }
  73338. for (var j = 0; j < bones.length; j++) {
  73339. if (bones[j].id === jointNode.id) {
  73340. newSkeleton.bones.push(bones[j]);
  73341. break;
  73342. }
  73343. }
  73344. }
  73345. newSkeleton.prepare();
  73346. // Finish
  73347. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  73348. newSkeleton.bones.push(nodesToRootToAdd[i]);
  73349. }
  73350. return newSkeleton;
  73351. };
  73352. /**
  73353. * Imports a mesh and its geometries
  73354. */
  73355. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  73356. if (!newMesh) {
  73357. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  73358. newMesh.id = id;
  73359. }
  73360. if (!node.babylonNode) {
  73361. return newMesh;
  73362. }
  73363. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  73364. if (!newMesh.material) {
  73365. newMesh.material = multiMat;
  73366. }
  73367. var vertexData = new BABYLON.VertexData();
  73368. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  73369. var verticesStarts = [];
  73370. var verticesCounts = [];
  73371. var indexStarts = [];
  73372. var indexCounts = [];
  73373. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  73374. var meshID = meshes[meshIndex];
  73375. var mesh = gltfRuntime.meshes[meshID];
  73376. if (!mesh) {
  73377. continue;
  73378. }
  73379. // Positions, normals and UVs
  73380. for (var i = 0; i < mesh.primitives.length; i++) {
  73381. // Temporary vertex data
  73382. var tempVertexData = new BABYLON.VertexData();
  73383. var primitive = mesh.primitives[i];
  73384. if (primitive.mode !== 4) {
  73385. // continue;
  73386. }
  73387. var attributes = primitive.attributes;
  73388. var accessor = null;
  73389. var buffer = null;
  73390. // Set positions, normal and uvs
  73391. for (var semantic in attributes) {
  73392. // Link accessor and buffer view
  73393. accessor = gltfRuntime.accessors[attributes[semantic]];
  73394. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  73395. if (semantic === "NORMAL") {
  73396. tempVertexData.normals = new Float32Array(buffer.length);
  73397. tempVertexData.normals.set(buffer);
  73398. }
  73399. else if (semantic === "POSITION") {
  73400. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  73401. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  73402. for (var j = 0; j < buffer.length; j += 4) {
  73403. tempVertexData.positions[j] = buffer[j];
  73404. tempVertexData.positions[j + 1] = buffer[j + 1];
  73405. tempVertexData.positions[j + 2] = buffer[j + 2];
  73406. }
  73407. }
  73408. else {
  73409. tempVertexData.positions = new Float32Array(buffer.length);
  73410. tempVertexData.positions.set(buffer);
  73411. }
  73412. verticesCounts.push(tempVertexData.positions.length);
  73413. }
  73414. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  73415. var channel = Number(semantic.split("_")[1]);
  73416. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  73417. var uvs = new Float32Array(buffer.length);
  73418. uvs.set(buffer);
  73419. normalizeUVs(uvs);
  73420. tempVertexData.set(uvs, uvKind);
  73421. }
  73422. else if (semantic === "JOINT") {
  73423. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  73424. tempVertexData.matricesIndices.set(buffer);
  73425. }
  73426. else if (semantic === "WEIGHT") {
  73427. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  73428. tempVertexData.matricesWeights.set(buffer);
  73429. }
  73430. else if (semantic === "COLOR") {
  73431. tempVertexData.colors = new Float32Array(buffer.length);
  73432. tempVertexData.colors.set(buffer);
  73433. }
  73434. }
  73435. // Indices
  73436. accessor = gltfRuntime.accessors[primitive.indices];
  73437. if (accessor) {
  73438. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  73439. tempVertexData.indices = new Int32Array(buffer.length);
  73440. tempVertexData.indices.set(buffer);
  73441. indexCounts.push(tempVertexData.indices.length);
  73442. }
  73443. else {
  73444. // Set indices on the fly
  73445. var indices = [];
  73446. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  73447. indices.push(j);
  73448. }
  73449. tempVertexData.indices = new Int32Array(indices);
  73450. indexCounts.push(tempVertexData.indices.length);
  73451. }
  73452. vertexData.merge(tempVertexData);
  73453. tempVertexData = undefined;
  73454. // Sub material
  73455. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  73456. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  73457. // Update vertices start and index start
  73458. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  73459. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  73460. }
  73461. }
  73462. // Apply geometry
  73463. geometry.setAllVerticesData(vertexData, false);
  73464. newMesh.computeWorldMatrix(true);
  73465. // Apply submeshes
  73466. newMesh.subMeshes = [];
  73467. var index = 0;
  73468. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  73469. var meshID = meshes[meshIndex];
  73470. var mesh = gltfRuntime.meshes[meshID];
  73471. if (!mesh) {
  73472. continue;
  73473. }
  73474. for (var i = 0; i < mesh.primitives.length; i++) {
  73475. if (mesh.primitives[i].mode !== 4) {
  73476. //continue;
  73477. }
  73478. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  73479. index++;
  73480. }
  73481. }
  73482. // Finish
  73483. return newMesh;
  73484. };
  73485. /**
  73486. * Configure node transformation from position, rotation and scaling
  73487. */
  73488. var configureNode = function (newNode, position, rotation, scaling) {
  73489. if (newNode.position) {
  73490. newNode.position = position;
  73491. }
  73492. if (newNode.rotationQuaternion || newNode.rotation) {
  73493. newNode.rotationQuaternion = rotation;
  73494. }
  73495. if (newNode.scaling) {
  73496. newNode.scaling = scaling;
  73497. }
  73498. };
  73499. /**
  73500. * Configures node from transformation matrix
  73501. */
  73502. var configureNodeFromMatrix = function (newNode, node, parent) {
  73503. if (node.matrix) {
  73504. var position = new BABYLON.Vector3(0, 0, 0);
  73505. var rotation = new BABYLON.Quaternion();
  73506. var scaling = new BABYLON.Vector3(0, 0, 0);
  73507. var mat = BABYLON.Matrix.FromArray(node.matrix);
  73508. mat.decompose(scaling, rotation, position);
  73509. configureNode(newNode, position, rotation, scaling);
  73510. }
  73511. else {
  73512. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  73513. }
  73514. newNode.computeWorldMatrix(true);
  73515. };
  73516. /**
  73517. * Imports a node
  73518. */
  73519. var importNode = function (gltfRuntime, node, id, parent) {
  73520. var lastNode = null;
  73521. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  73522. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  73523. return null;
  73524. }
  73525. }
  73526. // Meshes
  73527. if (node.skin) {
  73528. if (node.meshes) {
  73529. var skin = gltfRuntime.skins[node.skin];
  73530. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  73531. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  73532. if (newMesh.skeleton === null) {
  73533. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  73534. if (!skin.babylonSkeleton) {
  73535. skin.babylonSkeleton = newMesh.skeleton;
  73536. }
  73537. }
  73538. lastNode = newMesh;
  73539. }
  73540. }
  73541. else if (node.meshes) {
  73542. /**
  73543. * Improve meshes property
  73544. */
  73545. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  73546. lastNode = newMesh;
  73547. }
  73548. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  73549. var light = gltfRuntime.lights[node.light];
  73550. if (light) {
  73551. if (light.type === "ambient") {
  73552. var ambienLight = light[light.type];
  73553. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73554. hemiLight.name = node.name;
  73555. if (ambienLight.color) {
  73556. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  73557. }
  73558. lastNode = hemiLight;
  73559. }
  73560. else if (light.type === "directional") {
  73561. var directionalLight = light[light.type];
  73562. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73563. dirLight.name = node.name;
  73564. if (directionalLight.color) {
  73565. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  73566. }
  73567. lastNode = dirLight;
  73568. }
  73569. else if (light.type === "point") {
  73570. var pointLight = light[light.type];
  73571. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73572. ptLight.name = node.name;
  73573. if (pointLight.color) {
  73574. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  73575. }
  73576. lastNode = ptLight;
  73577. }
  73578. else if (light.type === "spot") {
  73579. var spotLight = light[light.type];
  73580. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  73581. spLight.name = node.name;
  73582. if (spotLight.color) {
  73583. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  73584. }
  73585. if (spotLight.fallOfAngle) {
  73586. spLight.angle = spotLight.fallOfAngle;
  73587. }
  73588. if (spotLight.fallOffExponent) {
  73589. spLight.exponent = spotLight.fallOffExponent;
  73590. }
  73591. lastNode = spLight;
  73592. }
  73593. }
  73594. }
  73595. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  73596. var camera = gltfRuntime.cameras[node.camera];
  73597. if (camera) {
  73598. if (camera.type === "orthographic") {
  73599. var orthographicCamera = camera[camera.type];
  73600. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73601. orthoCamera.name = node.name;
  73602. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  73603. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  73604. lastNode = orthoCamera;
  73605. }
  73606. else if (camera.type === "perspective") {
  73607. var perspectiveCamera = camera[camera.type];
  73608. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73609. persCamera.name = node.name;
  73610. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  73611. if (!perspectiveCamera.aspectRatio) {
  73612. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  73613. }
  73614. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  73615. persCamera.maxZ = perspectiveCamera.zfar;
  73616. persCamera.minZ = perspectiveCamera.znear;
  73617. }
  73618. lastNode = persCamera;
  73619. }
  73620. }
  73621. }
  73622. // Empty node
  73623. if (!node.jointName) {
  73624. if (node.babylonNode) {
  73625. return node.babylonNode;
  73626. }
  73627. else if (lastNode === null) {
  73628. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  73629. node.babylonNode = dummy;
  73630. lastNode = dummy;
  73631. }
  73632. }
  73633. if (lastNode !== null) {
  73634. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  73635. configureNodeFromMatrix(lastNode, node, parent);
  73636. }
  73637. else {
  73638. var translation = node.translation || [0, 0, 0];
  73639. var rotation = node.rotation || [0, 0, 0, 1];
  73640. var scale = node.scale || [1, 1, 1];
  73641. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  73642. }
  73643. lastNode.updateCache(true);
  73644. node.babylonNode = lastNode;
  73645. }
  73646. return lastNode;
  73647. };
  73648. /**
  73649. * Traverses nodes and creates them
  73650. */
  73651. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  73652. var node = gltfRuntime.nodes[id];
  73653. var newNode = null;
  73654. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  73655. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  73656. meshIncluded = true;
  73657. }
  73658. else {
  73659. meshIncluded = false;
  73660. }
  73661. }
  73662. else {
  73663. meshIncluded = true;
  73664. }
  73665. if (!node.jointName && meshIncluded) {
  73666. newNode = importNode(gltfRuntime, node, id, parent);
  73667. if (newNode !== null) {
  73668. newNode.id = id;
  73669. newNode.parent = parent;
  73670. }
  73671. }
  73672. if (node.children) {
  73673. for (var i = 0; i < node.children.length; i++) {
  73674. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  73675. }
  73676. }
  73677. };
  73678. /**
  73679. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  73680. */
  73681. var postLoad = function (gltfRuntime) {
  73682. // Nodes
  73683. var currentScene = gltfRuntime.currentScene;
  73684. if (currentScene) {
  73685. for (var i = 0; i < currentScene.nodes.length; i++) {
  73686. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73687. }
  73688. }
  73689. else {
  73690. for (var thing in gltfRuntime.scenes) {
  73691. currentScene = gltfRuntime.scenes[thing];
  73692. for (var i = 0; i < currentScene.nodes.length; i++) {
  73693. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73694. }
  73695. }
  73696. }
  73697. // Set animations
  73698. loadAnimations(gltfRuntime);
  73699. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  73700. var skeleton = gltfRuntime.scene.skeletons[i];
  73701. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  73702. }
  73703. };
  73704. /**
  73705. * onBind shaderrs callback to set uniforms and matrices
  73706. */
  73707. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  73708. var materialValues = material.values || technique.parameters;
  73709. for (var unif in unTreatedUniforms) {
  73710. var uniform = unTreatedUniforms[unif];
  73711. var type = uniform.type;
  73712. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  73713. if (uniform.semantic && !uniform.source && !uniform.node) {
  73714. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  73715. }
  73716. else if (uniform.semantic && (uniform.source || uniform.node)) {
  73717. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  73718. if (source === null) {
  73719. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  73720. }
  73721. if (source === null) {
  73722. continue;
  73723. }
  73724. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  73725. }
  73726. }
  73727. else {
  73728. var value = materialValues[technique.uniforms[unif]];
  73729. if (!value) {
  73730. continue;
  73731. }
  73732. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  73733. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  73734. if (texture === null || texture === undefined) {
  73735. continue;
  73736. }
  73737. shaderMaterial.getEffect().setTexture(unif, texture);
  73738. }
  73739. else {
  73740. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  73741. }
  73742. }
  73743. }
  73744. onSuccess(shaderMaterial);
  73745. };
  73746. /**
  73747. * Prepare uniforms to send the only one time
  73748. * Loads the appropriate textures
  73749. */
  73750. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  73751. var materialValues = material.values || technique.parameters;
  73752. var techniqueUniforms = technique.uniforms;
  73753. /**
  73754. * Prepare values here (not matrices)
  73755. */
  73756. for (var unif in unTreatedUniforms) {
  73757. var uniform = unTreatedUniforms[unif];
  73758. var type = uniform.type;
  73759. var value = materialValues[techniqueUniforms[unif]];
  73760. if (value === undefined) {
  73761. // In case the value is the same for all materials
  73762. value = uniform.value;
  73763. }
  73764. if (!value) {
  73765. continue;
  73766. }
  73767. var onLoadTexture = function (uniformName) {
  73768. return function (texture) {
  73769. if (uniform.value) {
  73770. // Static uniform
  73771. shaderMaterial.setTexture(uniformName, texture);
  73772. delete unTreatedUniforms[uniformName];
  73773. }
  73774. };
  73775. };
  73776. // Texture (sampler2D)
  73777. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  73778. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  73779. }
  73780. else {
  73781. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  73782. // Static uniform
  73783. delete unTreatedUniforms[unif];
  73784. }
  73785. }
  73786. }
  73787. };
  73788. /**
  73789. * Shader compilation failed
  73790. */
  73791. var onShaderCompileError = function (program, shaderMaterial, onError) {
  73792. return function (effect, error) {
  73793. shaderMaterial.dispose(true);
  73794. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  73795. };
  73796. };
  73797. /**
  73798. * Shader compilation success
  73799. */
  73800. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  73801. return function (_) {
  73802. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  73803. shaderMaterial.onBind = function (mesh) {
  73804. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  73805. };
  73806. };
  73807. };
  73808. /**
  73809. * Returns the appropriate uniform if already handled by babylon
  73810. */
  73811. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  73812. for (var unif in technique.uniforms) {
  73813. var uniform = technique.uniforms[unif];
  73814. var uniformParameter = technique.parameters[uniform];
  73815. if (tokenizer.currentIdentifier === unif) {
  73816. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  73817. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  73818. if (transformIndex !== -1) {
  73819. delete unTreatedUniforms[unif];
  73820. return babylonTransforms[transformIndex];
  73821. }
  73822. }
  73823. }
  73824. }
  73825. return tokenizer.currentIdentifier;
  73826. };
  73827. /**
  73828. * All shaders loaded. Create materials one by one
  73829. */
  73830. var importMaterials = function (gltfRuntime) {
  73831. // Create materials
  73832. for (var mat in gltfRuntime.materials) {
  73833. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  73834. }
  73835. };
  73836. /**
  73837. * Implementation of the base glTF spec
  73838. */
  73839. var GLTFLoaderBase = (function () {
  73840. function GLTFLoaderBase() {
  73841. }
  73842. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  73843. var gltfRuntime = {
  73844. extensions: {},
  73845. accessors: {},
  73846. buffers: {},
  73847. bufferViews: {},
  73848. meshes: {},
  73849. lights: {},
  73850. cameras: {},
  73851. nodes: {},
  73852. images: {},
  73853. textures: {},
  73854. shaders: {},
  73855. programs: {},
  73856. samplers: {},
  73857. techniques: {},
  73858. materials: {},
  73859. animations: {},
  73860. skins: {},
  73861. extensionsUsed: [],
  73862. scenes: {},
  73863. buffersCount: 0,
  73864. shaderscount: 0,
  73865. scene: scene,
  73866. rootUrl: rootUrl,
  73867. loadedBufferCount: 0,
  73868. loadedBufferViews: {},
  73869. loadedShaderCount: 0,
  73870. importOnlyMeshes: false,
  73871. dummyNodes: []
  73872. };
  73873. // Parse
  73874. if (parsedData.extensions) {
  73875. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  73876. }
  73877. if (parsedData.extensionsUsed) {
  73878. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  73879. }
  73880. if (parsedData.buffers) {
  73881. parseBuffers(parsedData.buffers, gltfRuntime);
  73882. }
  73883. if (parsedData.bufferViews) {
  73884. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  73885. }
  73886. if (parsedData.accessors) {
  73887. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  73888. }
  73889. if (parsedData.meshes) {
  73890. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  73891. }
  73892. if (parsedData.lights) {
  73893. parseObject(parsedData.lights, "lights", gltfRuntime);
  73894. }
  73895. if (parsedData.cameras) {
  73896. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  73897. }
  73898. if (parsedData.nodes) {
  73899. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  73900. }
  73901. if (parsedData.images) {
  73902. parseObject(parsedData.images, "images", gltfRuntime);
  73903. }
  73904. if (parsedData.textures) {
  73905. parseObject(parsedData.textures, "textures", gltfRuntime);
  73906. }
  73907. if (parsedData.shaders) {
  73908. parseShaders(parsedData.shaders, gltfRuntime);
  73909. }
  73910. if (parsedData.programs) {
  73911. parseObject(parsedData.programs, "programs", gltfRuntime);
  73912. }
  73913. if (parsedData.samplers) {
  73914. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  73915. }
  73916. if (parsedData.techniques) {
  73917. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  73918. }
  73919. if (parsedData.materials) {
  73920. parseObject(parsedData.materials, "materials", gltfRuntime);
  73921. }
  73922. if (parsedData.animations) {
  73923. parseObject(parsedData.animations, "animations", gltfRuntime);
  73924. }
  73925. if (parsedData.skins) {
  73926. parseObject(parsedData.skins, "skins", gltfRuntime);
  73927. }
  73928. if (parsedData.scenes) {
  73929. gltfRuntime.scenes = parsedData.scenes;
  73930. }
  73931. if (parsedData.scene && parsedData.scenes) {
  73932. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  73933. }
  73934. return gltfRuntime;
  73935. };
  73936. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  73937. var buffer = gltfRuntime.buffers[id];
  73938. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  73939. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  73940. }
  73941. else {
  73942. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  73943. onError(request.status + " " + request.statusText);
  73944. });
  73945. }
  73946. };
  73947. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  73948. var texture = gltfRuntime.textures[id];
  73949. if (!texture || !texture.source) {
  73950. onError(null);
  73951. return;
  73952. }
  73953. if (texture.babylonTexture) {
  73954. onSuccess(null);
  73955. return;
  73956. }
  73957. var source = gltfRuntime.images[texture.source];
  73958. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  73959. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  73960. }
  73961. else {
  73962. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  73963. onError(request.status + " " + request.statusText);
  73964. });
  73965. }
  73966. };
  73967. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  73968. var texture = gltfRuntime.textures[id];
  73969. if (texture.babylonTexture) {
  73970. onSuccess(texture.babylonTexture);
  73971. return;
  73972. }
  73973. var sampler = gltfRuntime.samplers[texture.sampler];
  73974. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  73975. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  73976. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  73977. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  73978. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  73979. var blob = new Blob([buffer]);
  73980. var blobURL = URL.createObjectURL(blob);
  73981. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  73982. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  73983. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  73984. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  73985. newTexture.name = id;
  73986. texture.babylonTexture = newTexture;
  73987. onSuccess(newTexture);
  73988. };
  73989. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  73990. var shader = gltfRuntime.shaders[id];
  73991. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  73992. var shaderString = atob(shader.uri.split(",")[1]);
  73993. onSuccess(shaderString);
  73994. }
  73995. else {
  73996. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  73997. onError(request.status + " " + request.statusText);
  73998. });
  73999. }
  74000. };
  74001. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74002. var material = gltfRuntime.materials[id];
  74003. var technique = gltfRuntime.techniques[material.technique];
  74004. if (!technique) {
  74005. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  74006. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  74007. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  74008. onSuccess(defaultMaterial);
  74009. return;
  74010. }
  74011. var program = gltfRuntime.programs[technique.program];
  74012. var states = technique.states;
  74013. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  74014. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  74015. var newVertexShader = "";
  74016. var newPixelShader = "";
  74017. var vertexTokenizer = new Tokenizer(vertexShader);
  74018. var pixelTokenizer = new Tokenizer(pixelShader);
  74019. var unTreatedUniforms = {};
  74020. var uniforms = [];
  74021. var attributes = [];
  74022. var samplers = [];
  74023. // Fill uniform, sampler2D and attributes
  74024. for (var unif in technique.uniforms) {
  74025. var uniform = technique.uniforms[unif];
  74026. var uniformParameter = technique.parameters[uniform];
  74027. unTreatedUniforms[unif] = uniformParameter;
  74028. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  74029. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  74030. if (transformIndex !== -1) {
  74031. uniforms.push(babylonTransforms[transformIndex]);
  74032. delete unTreatedUniforms[unif];
  74033. }
  74034. else {
  74035. uniforms.push(unif);
  74036. }
  74037. }
  74038. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  74039. samplers.push(unif);
  74040. }
  74041. else {
  74042. uniforms.push(unif);
  74043. }
  74044. }
  74045. for (var attr in technique.attributes) {
  74046. var attribute = technique.attributes[attr];
  74047. var attributeParameter = technique.parameters[attribute];
  74048. if (attributeParameter.semantic) {
  74049. attributes.push(getAttribute(attributeParameter));
  74050. }
  74051. }
  74052. // Configure vertex shader
  74053. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  74054. var tokenType = vertexTokenizer.currentToken;
  74055. if (tokenType !== ETokenType.IDENTIFIER) {
  74056. newVertexShader += vertexTokenizer.currentString;
  74057. continue;
  74058. }
  74059. var foundAttribute = false;
  74060. for (var attr in technique.attributes) {
  74061. var attribute = technique.attributes[attr];
  74062. var attributeParameter = technique.parameters[attribute];
  74063. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  74064. newVertexShader += getAttribute(attributeParameter);
  74065. foundAttribute = true;
  74066. break;
  74067. }
  74068. }
  74069. if (foundAttribute) {
  74070. continue;
  74071. }
  74072. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  74073. }
  74074. // Configure pixel shader
  74075. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  74076. var tokenType = pixelTokenizer.currentToken;
  74077. if (tokenType !== ETokenType.IDENTIFIER) {
  74078. newPixelShader += pixelTokenizer.currentString;
  74079. continue;
  74080. }
  74081. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  74082. }
  74083. // Create shader material
  74084. var shaderPath = {
  74085. vertex: program.vertexShader + id,
  74086. fragment: program.fragmentShader + id
  74087. };
  74088. var options = {
  74089. attributes: attributes,
  74090. uniforms: uniforms,
  74091. samplers: samplers,
  74092. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  74093. };
  74094. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  74095. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  74096. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  74097. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  74098. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  74099. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  74100. if (states && states.functions) {
  74101. var functions = states.functions;
  74102. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  74103. shaderMaterial.backFaceCulling = false;
  74104. }
  74105. var blendFunc = functions.blendFuncSeparate;
  74106. if (blendFunc) {
  74107. 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) {
  74108. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  74109. }
  74110. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  74111. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74112. }
  74113. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  74114. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  74115. }
  74116. 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) {
  74117. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  74118. }
  74119. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  74120. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  74121. }
  74122. 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) {
  74123. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  74124. }
  74125. }
  74126. }
  74127. };
  74128. return GLTFLoaderBase;
  74129. }());
  74130. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  74131. /**
  74132. * glTF V1 Loader
  74133. */
  74134. var GLTFLoader = (function () {
  74135. function GLTFLoader() {
  74136. }
  74137. GLTFLoader.RegisterExtension = function (extension) {
  74138. if (GLTFLoader.Extensions[extension.name]) {
  74139. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  74140. return;
  74141. }
  74142. GLTFLoader.Extensions[extension.name] = extension;
  74143. };
  74144. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  74145. var _this = this;
  74146. scene.useRightHandedSystem = true;
  74147. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  74148. gltfRuntime.importOnlyMeshes = true;
  74149. if (meshesNames === "") {
  74150. gltfRuntime.importMeshesNames = [];
  74151. }
  74152. else if (typeof meshesNames === "string") {
  74153. gltfRuntime.importMeshesNames = [meshesNames];
  74154. }
  74155. else if (meshesNames && !(meshesNames instanceof Array)) {
  74156. gltfRuntime.importMeshesNames = [meshesNames];
  74157. }
  74158. else {
  74159. gltfRuntime.importMeshesNames = [];
  74160. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  74161. }
  74162. // Create nodes
  74163. _this._createNodes(gltfRuntime);
  74164. var meshes = [];
  74165. var skeletons = [];
  74166. // Fill arrays of meshes and skeletons
  74167. for (var nde in gltfRuntime.nodes) {
  74168. var node = gltfRuntime.nodes[nde];
  74169. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  74170. meshes.push(node.babylonNode);
  74171. }
  74172. }
  74173. for (var skl in gltfRuntime.skins) {
  74174. var skin = gltfRuntime.skins[skl];
  74175. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  74176. skeletons.push(skin.babylonSkeleton);
  74177. }
  74178. }
  74179. // Load buffers, shaders, materials, etc.
  74180. _this._loadBuffersAsync(gltfRuntime, function () {
  74181. _this._loadShadersAsync(gltfRuntime, function () {
  74182. importMaterials(gltfRuntime);
  74183. postLoad(gltfRuntime);
  74184. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  74185. onSuccess(meshes, null, skeletons);
  74186. }
  74187. });
  74188. }, onProgress);
  74189. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  74190. onSuccess(meshes, null, skeletons);
  74191. }
  74192. }, onError);
  74193. return true;
  74194. };
  74195. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  74196. var _this = this;
  74197. scene.useRightHandedSystem = true;
  74198. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  74199. // Load runtime extensios
  74200. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  74201. // Create nodes
  74202. _this._createNodes(gltfRuntime);
  74203. // Load buffers, shaders, materials, etc.
  74204. _this._loadBuffersAsync(gltfRuntime, function () {
  74205. _this._loadShadersAsync(gltfRuntime, function () {
  74206. importMaterials(gltfRuntime);
  74207. postLoad(gltfRuntime);
  74208. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  74209. onSuccess();
  74210. }
  74211. });
  74212. });
  74213. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  74214. onSuccess();
  74215. }
  74216. }, onError);
  74217. }, onError);
  74218. };
  74219. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  74220. var hasShaders = false;
  74221. var processShader = function (sha, shader) {
  74222. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  74223. gltfRuntime.loadedShaderCount++;
  74224. if (shaderString) {
  74225. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  74226. }
  74227. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  74228. onload();
  74229. }
  74230. }, function () {
  74231. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  74232. });
  74233. };
  74234. for (var sha in gltfRuntime.shaders) {
  74235. hasShaders = true;
  74236. var shader = gltfRuntime.shaders[sha];
  74237. if (shader) {
  74238. processShader.bind(this, sha, shader)();
  74239. }
  74240. else {
  74241. BABYLON.Tools.Error("No shader named: " + sha);
  74242. }
  74243. }
  74244. if (!hasShaders) {
  74245. onload();
  74246. }
  74247. };
  74248. ;
  74249. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  74250. var hasBuffers = false;
  74251. var processBuffer = function (buf, buffer) {
  74252. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  74253. gltfRuntime.loadedBufferCount++;
  74254. if (bufferView) {
  74255. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  74256. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  74257. }
  74258. gltfRuntime.loadedBufferViews[buf] = bufferView;
  74259. }
  74260. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  74261. onLoad();
  74262. }
  74263. }, function () {
  74264. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  74265. });
  74266. };
  74267. for (var buf in gltfRuntime.buffers) {
  74268. hasBuffers = true;
  74269. var buffer = gltfRuntime.buffers[buf];
  74270. if (buffer) {
  74271. processBuffer.bind(this, buf, buffer)();
  74272. }
  74273. else {
  74274. BABYLON.Tools.Error("No buffer named: " + buf);
  74275. }
  74276. }
  74277. if (!hasBuffers) {
  74278. onLoad();
  74279. }
  74280. };
  74281. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  74282. var currentScene = gltfRuntime.currentScene;
  74283. if (currentScene) {
  74284. // Only one scene even if multiple scenes are defined
  74285. for (var i = 0; i < currentScene.nodes.length; i++) {
  74286. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  74287. }
  74288. }
  74289. else {
  74290. // Load all scenes
  74291. for (var thing in gltfRuntime.scenes) {
  74292. currentScene = gltfRuntime.scenes[thing];
  74293. for (var i = 0; i < currentScene.nodes.length; i++) {
  74294. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  74295. }
  74296. }
  74297. }
  74298. };
  74299. return GLTFLoader;
  74300. }());
  74301. GLTFLoader.Extensions = {};
  74302. GLTF1.GLTFLoader = GLTFLoader;
  74303. ;
  74304. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  74305. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74306. })(BABYLON || (BABYLON = {}));
  74307. //# sourceMappingURL=babylon.glTFLoader.js.map
  74308. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74309. var BABYLON;
  74310. (function (BABYLON) {
  74311. var GLTF1;
  74312. (function (GLTF1) {
  74313. /**
  74314. * Utils functions for GLTF
  74315. */
  74316. var GLTFUtils = (function () {
  74317. function GLTFUtils() {
  74318. }
  74319. /**
  74320. * Sets the given "parameter" matrix
  74321. * @param scene: the {BABYLON.Scene} object
  74322. * @param source: the source node where to pick the matrix
  74323. * @param parameter: the GLTF technique parameter
  74324. * @param uniformName: the name of the shader's uniform
  74325. * @param shaderMaterial: the shader material
  74326. */
  74327. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  74328. var mat = null;
  74329. if (parameter.semantic === "MODEL") {
  74330. mat = source.getWorldMatrix();
  74331. }
  74332. else if (parameter.semantic === "PROJECTION") {
  74333. mat = scene.getProjectionMatrix();
  74334. }
  74335. else if (parameter.semantic === "VIEW") {
  74336. mat = scene.getViewMatrix();
  74337. }
  74338. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  74339. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  74340. }
  74341. else if (parameter.semantic === "MODELVIEW") {
  74342. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  74343. }
  74344. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  74345. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  74346. }
  74347. else if (parameter.semantic === "MODELINVERSE") {
  74348. mat = source.getWorldMatrix().invert();
  74349. }
  74350. else if (parameter.semantic === "VIEWINVERSE") {
  74351. mat = scene.getViewMatrix().invert();
  74352. }
  74353. else if (parameter.semantic === "PROJECTIONINVERSE") {
  74354. mat = scene.getProjectionMatrix().invert();
  74355. }
  74356. else if (parameter.semantic === "MODELVIEWINVERSE") {
  74357. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  74358. }
  74359. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  74360. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  74361. }
  74362. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  74363. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  74364. }
  74365. else {
  74366. debugger;
  74367. }
  74368. switch (parameter.type) {
  74369. case GLTF1.EParameterType.FLOAT_MAT2:
  74370. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  74371. break;
  74372. case GLTF1.EParameterType.FLOAT_MAT3:
  74373. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  74374. break;
  74375. case GLTF1.EParameterType.FLOAT_MAT4:
  74376. shaderMaterial.setMatrix(uniformName, mat);
  74377. break;
  74378. default: break;
  74379. }
  74380. };
  74381. /**
  74382. * Sets the given "parameter" matrix
  74383. * @param shaderMaterial: the shader material
  74384. * @param uniform: the name of the shader's uniform
  74385. * @param value: the value of the uniform
  74386. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  74387. */
  74388. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  74389. switch (type) {
  74390. case GLTF1.EParameterType.FLOAT:
  74391. shaderMaterial.setFloat(uniform, value);
  74392. return true;
  74393. case GLTF1.EParameterType.FLOAT_VEC2:
  74394. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  74395. return true;
  74396. case GLTF1.EParameterType.FLOAT_VEC3:
  74397. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  74398. return true;
  74399. case GLTF1.EParameterType.FLOAT_VEC4:
  74400. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  74401. return true;
  74402. default: return false;
  74403. }
  74404. };
  74405. /**
  74406. * If the uri is a base64 string
  74407. * @param uri: the uri to test
  74408. */
  74409. GLTFUtils.IsBase64 = function (uri) {
  74410. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  74411. };
  74412. /**
  74413. * Decode the base64 uri
  74414. * @param uri: the uri to decode
  74415. */
  74416. GLTFUtils.DecodeBase64 = function (uri) {
  74417. var decodedString = atob(uri.split(",")[1]);
  74418. var bufferLength = decodedString.length;
  74419. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  74420. for (var i = 0; i < bufferLength; i++) {
  74421. bufferView[i] = decodedString.charCodeAt(i);
  74422. }
  74423. return bufferView.buffer;
  74424. };
  74425. /**
  74426. * Returns the wrap mode of the texture
  74427. * @param mode: the mode value
  74428. */
  74429. GLTFUtils.GetWrapMode = function (mode) {
  74430. switch (mode) {
  74431. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  74432. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  74433. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  74434. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  74435. }
  74436. };
  74437. /**
  74438. * Returns the byte stride giving an accessor
  74439. * @param accessor: the GLTF accessor objet
  74440. */
  74441. GLTFUtils.GetByteStrideFromType = function (accessor) {
  74442. // Needs this function since "byteStride" isn't requiered in glTF format
  74443. var type = accessor.type;
  74444. switch (type) {
  74445. case "VEC2": return 2;
  74446. case "VEC3": return 3;
  74447. case "VEC4": return 4;
  74448. case "MAT2": return 4;
  74449. case "MAT3": return 9;
  74450. case "MAT4": return 16;
  74451. default: return 1;
  74452. }
  74453. };
  74454. /**
  74455. * Returns the texture filter mode giving a mode value
  74456. * @param mode: the filter mode value
  74457. */
  74458. GLTFUtils.GetTextureFilterMode = function (mode) {
  74459. switch (mode) {
  74460. case GLTF1.ETextureFilterType.LINEAR:
  74461. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  74462. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  74463. case GLTF1.ETextureFilterType.NEAREST:
  74464. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  74465. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  74466. }
  74467. };
  74468. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  74469. var byteOffset = bufferView.byteOffset + byteOffset;
  74470. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  74471. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  74472. throw new Error("Buffer access is out of range");
  74473. }
  74474. var buffer = loadedBufferView.buffer;
  74475. byteOffset += loadedBufferView.byteOffset;
  74476. switch (componentType) {
  74477. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  74478. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  74479. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  74480. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  74481. default: return new Float32Array(buffer, byteOffset, byteLength);
  74482. }
  74483. };
  74484. /**
  74485. * Returns a buffer from its accessor
  74486. * @param gltfRuntime: the GLTF runtime
  74487. * @param accessor: the GLTF accessor
  74488. */
  74489. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  74490. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  74491. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  74492. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  74493. };
  74494. /**
  74495. * Decodes a buffer view into a string
  74496. * @param view: the buffer view
  74497. */
  74498. GLTFUtils.DecodeBufferToText = function (view) {
  74499. var result = "";
  74500. var length = view.byteLength;
  74501. for (var i = 0; i < length; ++i) {
  74502. result += String.fromCharCode(view[i]);
  74503. }
  74504. return result;
  74505. };
  74506. /**
  74507. * Returns the default material of gltf. Related to
  74508. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  74509. * @param scene: the Babylon.js scene
  74510. */
  74511. GLTFUtils.GetDefaultMaterial = function (scene) {
  74512. if (!GLTFUtils._DefaultMaterial) {
  74513. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  74514. "precision highp float;",
  74515. "",
  74516. "uniform mat4 worldView;",
  74517. "uniform mat4 projection;",
  74518. "",
  74519. "attribute vec3 position;",
  74520. "",
  74521. "void main(void)",
  74522. "{",
  74523. " gl_Position = projection * worldView * vec4(position, 1.0);",
  74524. "}"
  74525. ].join("\n");
  74526. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  74527. "precision highp float;",
  74528. "",
  74529. "uniform vec4 u_emission;",
  74530. "",
  74531. "void main(void)",
  74532. "{",
  74533. " gl_FragColor = u_emission;",
  74534. "}"
  74535. ].join("\n");
  74536. var shaderPath = {
  74537. vertex: "GLTFDefaultMaterial",
  74538. fragment: "GLTFDefaultMaterial"
  74539. };
  74540. var options = {
  74541. attributes: ["position"],
  74542. uniforms: ["worldView", "projection", "u_emission"],
  74543. samplers: [],
  74544. needAlphaBlending: false
  74545. };
  74546. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  74547. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  74548. }
  74549. return GLTFUtils._DefaultMaterial;
  74550. };
  74551. return GLTFUtils;
  74552. }());
  74553. // The GLTF default material
  74554. GLTFUtils._DefaultMaterial = null;
  74555. GLTF1.GLTFUtils = GLTFUtils;
  74556. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74557. })(BABYLON || (BABYLON = {}));
  74558. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  74559. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74560. var BABYLON;
  74561. (function (BABYLON) {
  74562. var GLTF1;
  74563. (function (GLTF1) {
  74564. var GLTFLoaderExtension = (function () {
  74565. function GLTFLoaderExtension(name) {
  74566. this._name = name;
  74567. }
  74568. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  74569. get: function () {
  74570. return this._name;
  74571. },
  74572. enumerable: true,
  74573. configurable: true
  74574. });
  74575. /**
  74576. * Defines an override for loading the runtime
  74577. * Return true to stop further extensions from loading the runtime
  74578. */
  74579. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74580. return false;
  74581. };
  74582. /**
  74583. * Defines an onverride for creating gltf runtime
  74584. * Return true to stop further extensions from creating the runtime
  74585. */
  74586. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74587. return false;
  74588. };
  74589. /**
  74590. * Defines an override for loading buffers
  74591. * Return true to stop further extensions from loading this buffer
  74592. */
  74593. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  74594. return false;
  74595. };
  74596. /**
  74597. * Defines an override for loading texture buffers
  74598. * Return true to stop further extensions from loading this texture data
  74599. */
  74600. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74601. return false;
  74602. };
  74603. /**
  74604. * Defines an override for creating textures
  74605. * Return true to stop further extensions from loading this texture
  74606. */
  74607. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  74608. return false;
  74609. };
  74610. /**
  74611. * Defines an override for loading shader strings
  74612. * Return true to stop further extensions from loading this shader data
  74613. */
  74614. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74615. return false;
  74616. };
  74617. /**
  74618. * Defines an override for loading materials
  74619. * Return true to stop further extensions from loading this material
  74620. */
  74621. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74622. return false;
  74623. };
  74624. // ---------
  74625. // Utilities
  74626. // ---------
  74627. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74628. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74629. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  74630. }, function () {
  74631. setTimeout(function () {
  74632. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  74633. });
  74634. });
  74635. };
  74636. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74637. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74638. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  74639. }, function () {
  74640. setTimeout(function () {
  74641. onSuccess();
  74642. });
  74643. });
  74644. };
  74645. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  74646. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74647. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  74648. }, function () {
  74649. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  74650. });
  74651. };
  74652. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  74653. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  74654. };
  74655. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74656. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74657. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  74658. }, function () {
  74659. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  74660. });
  74661. };
  74662. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74663. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74664. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  74665. }, function () {
  74666. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  74667. });
  74668. };
  74669. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74670. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74671. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  74672. }, function () {
  74673. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  74674. });
  74675. };
  74676. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  74677. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74678. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  74679. }, function () {
  74680. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  74681. });
  74682. };
  74683. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  74684. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  74685. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  74686. if (func(loaderExtension)) {
  74687. return;
  74688. }
  74689. }
  74690. defaultFunc();
  74691. };
  74692. return GLTFLoaderExtension;
  74693. }());
  74694. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  74695. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74696. })(BABYLON || (BABYLON = {}));
  74697. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  74698. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74699. var BABYLON;
  74700. (function (BABYLON) {
  74701. var GLTF1;
  74702. (function (GLTF1) {
  74703. var BinaryExtensionBufferName = "binary_glTF";
  74704. var EContentFormat;
  74705. (function (EContentFormat) {
  74706. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  74707. })(EContentFormat || (EContentFormat = {}));
  74708. ;
  74709. ;
  74710. ;
  74711. var GLTFBinaryExtension = (function (_super) {
  74712. __extends(GLTFBinaryExtension, _super);
  74713. function GLTFBinaryExtension() {
  74714. return _super.call(this, "KHR_binary_glTF") || this;
  74715. }
  74716. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74717. var extensionsUsed = data.json.extensionsUsed;
  74718. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  74719. return false;
  74720. }
  74721. this._bin = data.bin;
  74722. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  74723. return true;
  74724. };
  74725. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74726. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  74727. return false;
  74728. }
  74729. if (id !== BinaryExtensionBufferName) {
  74730. return false;
  74731. }
  74732. onSuccess(this._bin);
  74733. return true;
  74734. };
  74735. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74736. var texture = gltfRuntime.textures[id];
  74737. var source = gltfRuntime.images[texture.source];
  74738. if (!source.extensions || !(this.name in source.extensions)) {
  74739. return false;
  74740. }
  74741. var sourceExt = source.extensions[this.name];
  74742. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  74743. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  74744. onSuccess(buffer);
  74745. return true;
  74746. };
  74747. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74748. var shader = gltfRuntime.shaders[id];
  74749. if (!shader.extensions || !(this.name in shader.extensions)) {
  74750. return false;
  74751. }
  74752. var binaryExtensionShader = shader.extensions[this.name];
  74753. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  74754. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  74755. setTimeout(function () {
  74756. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  74757. onSuccess(shaderString);
  74758. });
  74759. return true;
  74760. };
  74761. return GLTFBinaryExtension;
  74762. }(GLTF1.GLTFLoaderExtension));
  74763. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  74764. var BinaryReader = (function () {
  74765. function BinaryReader(arrayBuffer) {
  74766. this._arrayBuffer = arrayBuffer;
  74767. this._dataView = new DataView(arrayBuffer);
  74768. this._byteOffset = 0;
  74769. }
  74770. BinaryReader.prototype.getUint32 = function () {
  74771. var value = this._dataView.getUint32(this._byteOffset, true);
  74772. this._byteOffset += 4;
  74773. return value;
  74774. };
  74775. BinaryReader.prototype.getUint8Array = function (length) {
  74776. if (!length) {
  74777. length = this._arrayBuffer.byteLength - this._byteOffset;
  74778. }
  74779. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  74780. this._byteOffset += length;
  74781. return value;
  74782. };
  74783. return BinaryReader;
  74784. }());
  74785. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  74786. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74787. })(BABYLON || (BABYLON = {}));
  74788. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  74789. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74790. var BABYLON;
  74791. (function (BABYLON) {
  74792. var GLTF1;
  74793. (function (GLTF1) {
  74794. ;
  74795. ;
  74796. ;
  74797. var GLTFMaterialsCommonExtension = (function (_super) {
  74798. __extends(GLTFMaterialsCommonExtension, _super);
  74799. function GLTFMaterialsCommonExtension() {
  74800. return _super.call(this, "KHR_materials_common") || this;
  74801. }
  74802. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74803. if (!gltfRuntime.extensions)
  74804. return false;
  74805. var extension = gltfRuntime.extensions[this.name];
  74806. if (!extension)
  74807. return false;
  74808. // Create lights
  74809. var lights = extension.lights;
  74810. if (lights) {
  74811. for (var thing in lights) {
  74812. var light = lights[thing];
  74813. switch (light.type) {
  74814. case "ambient":
  74815. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  74816. var ambient = light.ambient;
  74817. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  74818. break;
  74819. case "point":
  74820. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  74821. var point = light.point;
  74822. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  74823. break;
  74824. case "directional":
  74825. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  74826. var directional = light.directional;
  74827. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  74828. break;
  74829. case "spot":
  74830. var spot = light.spot;
  74831. 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);
  74832. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  74833. break;
  74834. default:
  74835. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  74836. break;
  74837. }
  74838. }
  74839. }
  74840. return false;
  74841. };
  74842. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74843. var material = gltfRuntime.materials[id];
  74844. if (!material || !material.extensions)
  74845. return false;
  74846. var extension = material.extensions[this.name];
  74847. if (!extension)
  74848. return false;
  74849. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  74850. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  74851. if (extension.technique === "CONSTANT") {
  74852. standardMaterial.disableLighting = true;
  74853. }
  74854. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  74855. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  74856. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  74857. // Ambient
  74858. if (typeof extension.values.ambient === "string") {
  74859. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  74860. }
  74861. else {
  74862. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  74863. }
  74864. // Diffuse
  74865. if (typeof extension.values.diffuse === "string") {
  74866. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  74867. }
  74868. else {
  74869. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  74870. }
  74871. // Emission
  74872. if (typeof extension.values.emission === "string") {
  74873. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  74874. }
  74875. else {
  74876. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  74877. }
  74878. // Specular
  74879. if (typeof extension.values.specular === "string") {
  74880. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  74881. }
  74882. else {
  74883. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  74884. }
  74885. return true;
  74886. };
  74887. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  74888. // Create buffer from texture url
  74889. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  74890. // Create texture from buffer
  74891. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  74892. }, onError);
  74893. };
  74894. return GLTFMaterialsCommonExtension;
  74895. }(GLTF1.GLTFLoaderExtension));
  74896. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  74897. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  74898. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74899. })(BABYLON || (BABYLON = {}));
  74900. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  74901. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74902. var BABYLON;
  74903. (function (BABYLON) {
  74904. var GLTF2;
  74905. (function (GLTF2) {
  74906. /**
  74907. * Enums
  74908. */
  74909. var EComponentType;
  74910. (function (EComponentType) {
  74911. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  74912. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  74913. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  74914. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  74915. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  74916. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  74917. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  74918. var EMeshPrimitiveMode;
  74919. (function (EMeshPrimitiveMode) {
  74920. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  74921. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  74922. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  74923. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  74924. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  74925. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  74926. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  74927. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  74928. var ETextureMagFilter;
  74929. (function (ETextureMagFilter) {
  74930. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  74931. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  74932. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  74933. var ETextureMinFilter;
  74934. (function (ETextureMinFilter) {
  74935. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  74936. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  74937. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  74938. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  74939. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  74940. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  74941. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  74942. var ETextureWrapMode;
  74943. (function (ETextureWrapMode) {
  74944. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  74945. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  74946. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  74947. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  74948. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  74949. })(BABYLON || (BABYLON = {}));
  74950. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  74951. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74952. var BABYLON;
  74953. (function (BABYLON) {
  74954. var GLTF2;
  74955. (function (GLTF2) {
  74956. var GLTFLoaderTracker = (function () {
  74957. function GLTFLoaderTracker(onComplete) {
  74958. this._pendingCount = 0;
  74959. this._callback = onComplete;
  74960. }
  74961. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  74962. this._pendingCount++;
  74963. };
  74964. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  74965. if (--this._pendingCount === 0) {
  74966. this._callback();
  74967. }
  74968. };
  74969. return GLTFLoaderTracker;
  74970. }());
  74971. var GLTFLoader = (function () {
  74972. function GLTFLoader(parent) {
  74973. this._renderReady = false;
  74974. this._disposed = false;
  74975. this._renderReadyObservable = new BABYLON.Observable();
  74976. // Count of pending work that needs to complete before the asset is rendered.
  74977. this._renderPendingCount = 0;
  74978. // Count of pending work that needs to complete before the loader is disposed.
  74979. this._loaderPendingCount = 0;
  74980. this._loaderTrackers = new Array();
  74981. this._parent = parent;
  74982. }
  74983. GLTFLoader.RegisterExtension = function (extension) {
  74984. if (GLTFLoader.Extensions[extension.name]) {
  74985. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  74986. return;
  74987. }
  74988. GLTFLoader.Extensions[extension.name] = extension;
  74989. // Keep the order of registration so that extensions registered first are called first.
  74990. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  74991. };
  74992. GLTFLoader.prototype.dispose = function () {
  74993. if (this._disposed) {
  74994. return;
  74995. }
  74996. this._disposed = true;
  74997. // Revoke object urls created during load
  74998. if (this._gltf.textures) {
  74999. this._gltf.textures.forEach(function (texture) {
  75000. if (texture.url) {
  75001. URL.revokeObjectURL(texture.url);
  75002. }
  75003. });
  75004. }
  75005. this._gltf = undefined;
  75006. this._babylonScene = undefined;
  75007. this._rootUrl = undefined;
  75008. this._defaultMaterial = undefined;
  75009. this._successCallback = undefined;
  75010. this._errorCallback = undefined;
  75011. this._renderReady = false;
  75012. this._renderReadyObservable.clear();
  75013. this._renderPendingCount = 0;
  75014. this._loaderPendingCount = 0;
  75015. };
  75016. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  75017. var _this = this;
  75018. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  75019. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  75020. }, onProgress, onError);
  75021. };
  75022. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  75023. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  75024. };
  75025. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  75026. try {
  75027. this._loadData(data);
  75028. this._babylonScene = scene;
  75029. this._rootUrl = rootUrl;
  75030. this._successCallback = onSuccess;
  75031. this._progressCallback = onProgress;
  75032. this._errorCallback = onError;
  75033. this._addPendingData(this);
  75034. this._loadScene(nodeNames);
  75035. this._loadAnimations();
  75036. this._removePendingData(this);
  75037. }
  75038. catch (e) {
  75039. this._onError(e.message);
  75040. }
  75041. };
  75042. GLTFLoader.prototype._onError = function (message) {
  75043. if (this._disposed) {
  75044. return;
  75045. }
  75046. BABYLON.Tools.Error("glTF Loader Error: " + message);
  75047. if (this._errorCallback) {
  75048. this._errorCallback(message);
  75049. }
  75050. this.dispose();
  75051. };
  75052. GLTFLoader.prototype._onProgress = function (event) {
  75053. if (this._disposed) {
  75054. return;
  75055. }
  75056. if (this._progressCallback) {
  75057. this._progressCallback(event);
  75058. }
  75059. };
  75060. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  75061. if (this._renderReady) {
  75062. func();
  75063. }
  75064. else {
  75065. this._renderReadyObservable.add(func);
  75066. }
  75067. };
  75068. GLTFLoader.prototype._onRenderReady = function () {
  75069. this._rootNode.babylonMesh.setEnabled(true);
  75070. this._startAnimations();
  75071. this._successCallback();
  75072. this._renderReadyObservable.notifyObservers(this);
  75073. if (this._parent.onReady) {
  75074. this._parent.onReady();
  75075. }
  75076. };
  75077. GLTFLoader.prototype._onComplete = function () {
  75078. if (this._parent.onComplete) {
  75079. this._parent.onComplete();
  75080. }
  75081. this.dispose();
  75082. };
  75083. GLTFLoader.prototype._loadData = function (data) {
  75084. this._gltf = data.json;
  75085. if (data.bin) {
  75086. var buffers = this._gltf.buffers;
  75087. if (buffers && buffers[0] && !buffers[0].uri) {
  75088. var binaryBuffer = buffers[0];
  75089. if (binaryBuffer.byteLength != data.bin.byteLength) {
  75090. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  75091. }
  75092. binaryBuffer.loadedData = data.bin;
  75093. }
  75094. else {
  75095. BABYLON.Tools.Warn("Unexpected BIN chunk");
  75096. }
  75097. }
  75098. };
  75099. GLTFLoader.prototype._getMeshes = function () {
  75100. var meshes = [this._rootNode.babylonMesh];
  75101. var nodes = this._gltf.nodes;
  75102. if (nodes) {
  75103. nodes.forEach(function (node) {
  75104. if (node.babylonMesh) {
  75105. meshes.push(node.babylonMesh);
  75106. }
  75107. });
  75108. }
  75109. return meshes;
  75110. };
  75111. GLTFLoader.prototype._getSkeletons = function () {
  75112. var skeletons = [];
  75113. var skins = this._gltf.skins;
  75114. if (skins) {
  75115. skins.forEach(function (skin) {
  75116. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  75117. skeletons.push(skin.babylonSkeleton);
  75118. }
  75119. });
  75120. }
  75121. return skeletons;
  75122. };
  75123. GLTFLoader.prototype._getAnimationTargets = function () {
  75124. var targets = [];
  75125. var animations = this._gltf.animations;
  75126. if (animations) {
  75127. animations.forEach(function (animation) {
  75128. targets.push.apply(targets, animation.targets);
  75129. });
  75130. }
  75131. return targets;
  75132. };
  75133. GLTFLoader.prototype._startAnimations = function () {
  75134. var _this = this;
  75135. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  75136. };
  75137. GLTFLoader.prototype._loadScene = function (nodeNames) {
  75138. var scene = this._getArrayItem(this._gltf.scenes, this._gltf.scene || 0, "Scene");
  75139. if (!scene) {
  75140. return;
  75141. }
  75142. this._rootNode = { name: "__root__" };
  75143. switch (this._parent.coordinateSystemMode) {
  75144. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  75145. if (!this._babylonScene.useRightHandedSystem) {
  75146. this._rootNode.rotation = [0, 1, 0, 0];
  75147. this._rootNode.scale = [1, 1, -1];
  75148. }
  75149. break;
  75150. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  75151. // do nothing
  75152. break;
  75153. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  75154. this._babylonScene.useRightHandedSystem = true;
  75155. break;
  75156. default:
  75157. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  75158. return;
  75159. }
  75160. this._loadNode(this._rootNode);
  75161. var nodeIndices = scene.nodes;
  75162. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  75163. node.index = index;
  75164. node.parent = parentNode;
  75165. return true;
  75166. }, this._rootNode);
  75167. var materials = this._gltf.materials;
  75168. if (materials) {
  75169. materials.forEach(function (material, index) { return material.index = index; });
  75170. }
  75171. var skins = this._gltf.skins;
  75172. if (skins) {
  75173. skins.forEach(function (skin, index) { return skin.index = index; });
  75174. }
  75175. if (nodeNames) {
  75176. if (!(nodeNames instanceof Array)) {
  75177. nodeNames = [nodeNames];
  75178. }
  75179. var filteredNodeIndices = new Array();
  75180. this._traverseNodes(nodeIndices, function (node) {
  75181. if (nodeNames.indexOf(node.name) !== -1) {
  75182. filteredNodeIndices.push(node.index);
  75183. return false;
  75184. }
  75185. return true;
  75186. }, this._rootNode);
  75187. nodeIndices = filteredNodeIndices;
  75188. }
  75189. for (var i = 0; i < nodeIndices.length; i++) {
  75190. var node = this._getArrayItem(this._gltf.nodes, nodeIndices[i], "Node");
  75191. if (!node) {
  75192. return;
  75193. }
  75194. this._loadNode(node);
  75195. }
  75196. // Disable the root mesh until the asset is ready to render.
  75197. this._rootNode.babylonMesh.setEnabled(false);
  75198. };
  75199. GLTFLoader.prototype._loadNode = function (node) {
  75200. if (GLTF2.GLTFLoaderExtension.LoadNode(this, node)) {
  75201. return;
  75202. }
  75203. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  75204. this._loadTransform(node);
  75205. if (node.mesh !== undefined) {
  75206. var mesh = this._getArrayItem(this._gltf.meshes, node.mesh, "Mesh");
  75207. if (!mesh) {
  75208. return;
  75209. }
  75210. this._loadMesh(node, mesh);
  75211. }
  75212. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  75213. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  75214. node.babylonAnimationTargets.push(node.babylonMesh);
  75215. if (node.skin !== undefined) {
  75216. var skin = this._getArrayItem(this._gltf.skins, node.skin, "Skin");
  75217. if (!skin) {
  75218. return;
  75219. }
  75220. node.babylonMesh.skeleton = this._loadSkin(skin);
  75221. }
  75222. if (node.camera !== undefined) {
  75223. // TODO: handle cameras
  75224. }
  75225. if (node.children) {
  75226. for (var i = 0; i < node.children.length; i++) {
  75227. var childNode = this._getArrayItem(this._gltf.nodes, node.children[i], "Node");
  75228. if (!childNode) {
  75229. return;
  75230. }
  75231. this._loadNode(childNode);
  75232. }
  75233. }
  75234. };
  75235. GLTFLoader.prototype._loadMesh = function (node, mesh) {
  75236. var _this = this;
  75237. node.babylonMesh.name = mesh.name || node.babylonMesh.name;
  75238. var babylonMultiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  75239. node.babylonMesh.material = babylonMultiMaterial;
  75240. var geometry = new BABYLON.Geometry(node.babylonMesh.name, this._babylonScene, null, false, node.babylonMesh);
  75241. var vertexData = new BABYLON.VertexData();
  75242. vertexData.positions = [];
  75243. vertexData.indices = [];
  75244. var subMeshInfos = [];
  75245. var loadedPrimitives = 0;
  75246. var totalPrimitives = mesh.primitives.length;
  75247. var _loop_1 = function (i) {
  75248. var primitive = mesh.primitives[i];
  75249. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  75250. // TODO: handle other primitive modes
  75251. throw new Error("Not implemented");
  75252. }
  75253. this_1._createMorphTargets(node, mesh, primitive, node.babylonMesh);
  75254. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  75255. _this._loadMorphTargetsData(mesh, primitive, subVertexData, node.babylonMesh);
  75256. subMeshInfos.push({
  75257. materialIndex: i,
  75258. verticesStart: vertexData.positions.length,
  75259. verticesCount: subVertexData.positions.length,
  75260. indicesStart: vertexData.indices.length,
  75261. indicesCount: subVertexData.indices.length,
  75262. loadMaterial: function () {
  75263. if (primitive.material == null) {
  75264. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  75265. return;
  75266. }
  75267. var material = _this._getArrayItem(_this._gltf.materials, primitive.material, "Material");
  75268. if (!material) {
  75269. return;
  75270. }
  75271. _this._loadMaterial(material, function (babylonMaterial, isNew) {
  75272. if (isNew && _this._parent.onMaterialLoaded) {
  75273. _this._parent.onMaterialLoaded(babylonMaterial);
  75274. }
  75275. if (_this._parent.onBeforeMaterialReadyAsync) {
  75276. _this._addLoaderPendingData(material);
  75277. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  75278. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  75279. _this._removeLoaderPendingData(material);
  75280. });
  75281. }
  75282. else {
  75283. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  75284. }
  75285. });
  75286. }
  75287. });
  75288. vertexData.merge(subVertexData);
  75289. if (++loadedPrimitives === totalPrimitives) {
  75290. geometry.setAllVerticesData(vertexData, false);
  75291. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  75292. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  75293. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  75294. node.babylonMesh.subMeshes = [];
  75295. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, node.babylonMesh); });
  75296. }
  75297. });
  75298. };
  75299. var this_1 = this;
  75300. for (var i = 0; i < totalPrimitives; i++) {
  75301. _loop_1(i);
  75302. }
  75303. };
  75304. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  75305. var _this = this;
  75306. var attributes = primitive.attributes;
  75307. if (!attributes) {
  75308. this._onError("Primitive has no attributes");
  75309. return;
  75310. }
  75311. var vertexData = new BABYLON.VertexData();
  75312. var loadedAttributes = 0;
  75313. var totalAttributes = Object.keys(attributes).length;
  75314. var _loop_2 = function (attribute) {
  75315. accessor = this_2._getArrayItem(this_2._gltf.accessors, attributes[attribute], "Mesh primitive attribute '" + attribute + "' accessor");
  75316. if (!accessor) {
  75317. return { value: void 0 };
  75318. }
  75319. this_2._loadAccessorAsync(accessor, function (data) {
  75320. switch (attribute) {
  75321. case "NORMAL":
  75322. vertexData.normals = data;
  75323. break;
  75324. case "POSITION":
  75325. vertexData.positions = data;
  75326. break;
  75327. case "TANGENT":
  75328. vertexData.tangents = data;
  75329. break;
  75330. case "TEXCOORD_0":
  75331. vertexData.uvs = data;
  75332. break;
  75333. case "TEXCOORD_1":
  75334. vertexData.uvs2 = data;
  75335. break;
  75336. case "JOINTS_0":
  75337. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  75338. break;
  75339. case "WEIGHTS_0":
  75340. vertexData.matricesWeights = data;
  75341. break;
  75342. case "COLOR_0":
  75343. vertexData.colors = data;
  75344. break;
  75345. default:
  75346. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  75347. break;
  75348. }
  75349. if (++loadedAttributes === totalAttributes) {
  75350. if (primitive.indices == null) {
  75351. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  75352. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  75353. onSuccess(vertexData);
  75354. }
  75355. else {
  75356. var indicesAccessor = _this._getArrayItem(_this._gltf.accessors, primitive.indices, "Mesh primitive 'indices' accessor");
  75357. if (!indicesAccessor) {
  75358. return;
  75359. }
  75360. _this._loadAccessorAsync(indicesAccessor, function (data) {
  75361. vertexData.indices = data;
  75362. onSuccess(vertexData);
  75363. });
  75364. }
  75365. }
  75366. });
  75367. };
  75368. var this_2 = this, accessor;
  75369. for (var attribute in attributes) {
  75370. var state_1 = _loop_2(attribute);
  75371. if (typeof state_1 === "object")
  75372. return state_1.value;
  75373. }
  75374. };
  75375. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  75376. var targets = primitive.targets;
  75377. if (!targets) {
  75378. return;
  75379. }
  75380. if (!babylonMesh.morphTargetManager) {
  75381. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  75382. }
  75383. for (var index = 0; index < targets.length; index++) {
  75384. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  75385. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  75386. }
  75387. };
  75388. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  75389. var targets = primitive.targets;
  75390. if (!targets) {
  75391. return;
  75392. }
  75393. var _loop_3 = function () {
  75394. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  75395. attributes = targets[index];
  75396. var _loop_4 = function (attribute) {
  75397. accessor = this_3._getArrayItem(this_3._gltf.accessors, attributes[attribute], "Mesh primitive morph target attribute '" + attribute + "' accessor");
  75398. if (!accessor) {
  75399. return { value: void 0 };
  75400. }
  75401. this_3._loadAccessorAsync(accessor, function (data) {
  75402. if (accessor.name) {
  75403. babylonMorphTarget.name = accessor.name;
  75404. }
  75405. // glTF stores morph target information as deltas while babylon.js expects the final data.
  75406. // As a result we have to add the original data to the delta to calculate the final data.
  75407. var values = data;
  75408. switch (attribute) {
  75409. case "NORMAL":
  75410. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  75411. babylonMorphTarget.setNormals(values);
  75412. break;
  75413. case "POSITION":
  75414. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  75415. babylonMorphTarget.setPositions(values);
  75416. break;
  75417. case "TANGENT":
  75418. // Tangent data for morph targets is stored as xyz delta.
  75419. // The vertexData.tangent is stored as xyzw.
  75420. // So we need to skip every fourth vertexData.tangent.
  75421. for (var i = 0, j = 0; i < values.length; i++, j++) {
  75422. values[i] += vertexData.tangents[j];
  75423. if ((i + 1) % 3 == 0) {
  75424. j++;
  75425. }
  75426. }
  75427. babylonMorphTarget.setTangents(values);
  75428. break;
  75429. default:
  75430. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  75431. break;
  75432. }
  75433. });
  75434. };
  75435. for (var attribute in attributes) {
  75436. var state_2 = _loop_4(attribute);
  75437. if (typeof state_2 === "object")
  75438. return state_2;
  75439. }
  75440. };
  75441. var this_3 = this, attributes, accessor;
  75442. for (var index = 0; index < targets.length; index++) {
  75443. var state_3 = _loop_3();
  75444. if (typeof state_3 === "object")
  75445. return state_3.value;
  75446. }
  75447. };
  75448. GLTFLoader.prototype._loadTransform = function (node) {
  75449. var position = BABYLON.Vector3.Zero();
  75450. var rotation = BABYLON.Quaternion.Identity();
  75451. var scaling = BABYLON.Vector3.One();
  75452. if (node.matrix) {
  75453. var mat = BABYLON.Matrix.FromArray(node.matrix);
  75454. mat.decompose(scaling, rotation, position);
  75455. }
  75456. else {
  75457. if (node.translation)
  75458. position = BABYLON.Vector3.FromArray(node.translation);
  75459. if (node.rotation)
  75460. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  75461. if (node.scale)
  75462. scaling = BABYLON.Vector3.FromArray(node.scale);
  75463. }
  75464. node.babylonMesh.position = position;
  75465. node.babylonMesh.rotationQuaternion = rotation;
  75466. node.babylonMesh.scaling = scaling;
  75467. };
  75468. GLTFLoader.prototype._loadSkin = function (skin) {
  75469. var _this = this;
  75470. var skeletonId = "skeleton" + skin.index;
  75471. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  75472. if (skin.inverseBindMatrices == null) {
  75473. this._loadBones(skin, null);
  75474. }
  75475. else {
  75476. var accessor = this._getArrayItem(this._gltf.accessors, skin.inverseBindMatrices, "Skin (" + skin.index + ") inverse bind matrices attribute accessor");
  75477. if (!accessor) {
  75478. return;
  75479. }
  75480. this._loadAccessorAsync(accessor, function (data) {
  75481. _this._loadBones(skin, data);
  75482. });
  75483. }
  75484. return skin.babylonSkeleton;
  75485. };
  75486. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  75487. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  75488. node.babylonBones = node.babylonBones || {};
  75489. node.babylonBones[skin.index] = babylonBone;
  75490. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  75491. node.babylonAnimationTargets.push(babylonBone);
  75492. return babylonBone;
  75493. };
  75494. GLTFLoader.prototype._loadBones = function (skin, inverseBindMatrixData) {
  75495. var babylonBones = {};
  75496. for (var i = 0; i < skin.joints.length; i++) {
  75497. var node = this._getArrayItem(this._gltf.nodes, skin.joints[i], "Skin (" + skin.index + ") joint");
  75498. if (!node) {
  75499. return;
  75500. }
  75501. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  75502. }
  75503. };
  75504. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  75505. var babylonBone = babylonBones[node.index];
  75506. if (babylonBone) {
  75507. return babylonBone;
  75508. }
  75509. var boneIndex = skin.joints.indexOf(node.index);
  75510. var baseMatrix = BABYLON.Matrix.Identity();
  75511. if (inverseBindMatrixData && boneIndex !== -1) {
  75512. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  75513. baseMatrix.invertToRef(baseMatrix);
  75514. }
  75515. var babylonParentBone;
  75516. if (node.index != skin.skeleton && node.parent) {
  75517. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  75518. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  75519. }
  75520. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  75521. babylonBones[node.index] = babylonBone;
  75522. return babylonBone;
  75523. };
  75524. GLTFLoader.prototype._getNodeMatrix = function (node) {
  75525. return node.matrix ?
  75526. BABYLON.Matrix.FromArray(node.matrix) :
  75527. 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());
  75528. };
  75529. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  75530. if (parentNode === void 0) { parentNode = null; }
  75531. for (var i = 0; i < indices.length; i++) {
  75532. this._traverseNode(indices[i], action, parentNode);
  75533. }
  75534. };
  75535. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  75536. if (parentNode === void 0) { parentNode = null; }
  75537. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, index, action, parentNode)) {
  75538. return;
  75539. }
  75540. var node = this._getArrayItem(this._gltf.nodes, index, "Node");
  75541. if (!node) {
  75542. return;
  75543. }
  75544. if (!action(node, index, parentNode)) {
  75545. return;
  75546. }
  75547. if (node.children) {
  75548. this._traverseNodes(node.children, action, node);
  75549. }
  75550. };
  75551. GLTFLoader.prototype._loadAnimations = function () {
  75552. var animations = this._gltf.animations;
  75553. if (!animations) {
  75554. return;
  75555. }
  75556. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  75557. var animation = animations[animationIndex];
  75558. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  75559. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  75560. }
  75561. }
  75562. };
  75563. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  75564. var channel = animation.channels[channelIndex];
  75565. var samplerIndex = channel.sampler;
  75566. var sampler = animation.samplers[samplerIndex];
  75567. var targetNode = this._getArrayItem(this._gltf.nodes, channel.target.node, "Animation channel target");
  75568. if (!targetNode) {
  75569. return;
  75570. }
  75571. var targetPath = {
  75572. "translation": "position",
  75573. "rotation": "rotationQuaternion",
  75574. "scale": "scaling",
  75575. "weights": "influence"
  75576. }[channel.target.path];
  75577. if (!targetPath) {
  75578. this._onError("Invalid animation channel target path '" + channel.target.path + "'");
  75579. return;
  75580. }
  75581. var animationType = {
  75582. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  75583. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  75584. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  75585. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  75586. }[targetPath];
  75587. var inputData;
  75588. var outputData;
  75589. var checkSuccess = function () {
  75590. if (!inputData || !outputData) {
  75591. return;
  75592. }
  75593. var outputBufferOffset = 0;
  75594. var getNextOutputValue = {
  75595. "position": function () {
  75596. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  75597. outputBufferOffset += 3;
  75598. return value;
  75599. },
  75600. "rotationQuaternion": function () {
  75601. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  75602. outputBufferOffset += 4;
  75603. return value;
  75604. },
  75605. "scaling": function () {
  75606. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  75607. outputBufferOffset += 3;
  75608. return value;
  75609. },
  75610. "influence": function () {
  75611. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  75612. var value = new Array(numTargets);
  75613. for (var i = 0; i < numTargets; i++) {
  75614. value[i] = outputData[outputBufferOffset++];
  75615. }
  75616. return value;
  75617. },
  75618. }[targetPath];
  75619. var getNextKey = {
  75620. "LINEAR": function (frameIndex) { return ({
  75621. frame: inputData[frameIndex],
  75622. value: getNextOutputValue()
  75623. }); },
  75624. "CUBICSPLINE": function (frameIndex) { return ({
  75625. frame: inputData[frameIndex],
  75626. inTangent: getNextOutputValue(),
  75627. value: getNextOutputValue(),
  75628. outTangent: getNextOutputValue()
  75629. }); },
  75630. }[sampler.interpolation];
  75631. var keys = new Array(inputData.length);
  75632. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  75633. keys[frameIndex] = getNextKey(frameIndex);
  75634. }
  75635. animation.targets = animation.targets || [];
  75636. if (targetPath === "influence") {
  75637. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  75638. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  75639. var morphTarget = morphTargetManager.getTarget(targetIndex);
  75640. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  75641. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  75642. babylonAnimation.setKeys(keys.map(function (key) { return ({
  75643. frame: key.frame,
  75644. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  75645. value: key.value[targetIndex],
  75646. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  75647. }); }));
  75648. morphTarget.animations.push(babylonAnimation);
  75649. animation.targets.push(morphTarget);
  75650. }
  75651. }
  75652. else {
  75653. var animationName = animation.name || "anim" + animationIndex;
  75654. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  75655. babylonAnimation.setKeys(keys);
  75656. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  75657. var target = targetNode.babylonAnimationTargets[i];
  75658. target.animations.push(babylonAnimation.clone());
  75659. animation.targets.push(target);
  75660. }
  75661. }
  75662. };
  75663. var inputAccessor = this._getArrayItem(this._gltf.accessors, sampler.input, "Animation sampler input accessor");
  75664. if (!inputAccessor) {
  75665. return;
  75666. }
  75667. this._loadAccessorAsync(inputAccessor, function (data) {
  75668. inputData = data;
  75669. checkSuccess();
  75670. });
  75671. var outputAccessor = this._getArrayItem(this._gltf.accessors, sampler.output, "Animation sampler output accessor");
  75672. if (!outputAccessor) {
  75673. return;
  75674. }
  75675. this._loadAccessorAsync(outputAccessor, function (data) {
  75676. outputData = data;
  75677. checkSuccess();
  75678. });
  75679. };
  75680. GLTFLoader.prototype._validateUri = function (uri) {
  75681. if (!uri) {
  75682. this._onError("Uri is missing");
  75683. return false;
  75684. }
  75685. return true;
  75686. };
  75687. GLTFLoader.prototype._loadBufferAsync = function (buffer, onSuccess) {
  75688. var _this = this;
  75689. this._addPendingData(buffer);
  75690. if (buffer.loadedData) {
  75691. setTimeout(function () {
  75692. onSuccess(buffer.loadedData);
  75693. _this._removePendingData(buffer);
  75694. });
  75695. }
  75696. else if (buffer.loadedObservable) {
  75697. buffer.loadedObservable.add(function (buffer) {
  75698. onSuccess(buffer.loadedData);
  75699. _this._removePendingData(buffer);
  75700. });
  75701. }
  75702. else if (this._validateUri(buffer.uri)) {
  75703. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  75704. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  75705. buffer.loadedData = new Uint8Array(data);
  75706. setTimeout(function () {
  75707. onSuccess(buffer.loadedData);
  75708. _this._removePendingData(buffer);
  75709. });
  75710. }
  75711. else {
  75712. buffer.loadedObservable = new BABYLON.Observable();
  75713. buffer.loadedObservable.add(function (buffer) {
  75714. onSuccess(buffer.loadedData);
  75715. _this._removePendingData(buffer);
  75716. });
  75717. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  75718. buffer.loadedData = new Uint8Array(data);
  75719. buffer.loadedObservable.notifyObservers(buffer);
  75720. buffer.loadedObservable = null;
  75721. }, function (event) {
  75722. _this._onProgress(event);
  75723. }, this._babylonScene.database, true, function (request) {
  75724. _this._onError("Failed to load file '" + buffer.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  75725. });
  75726. }
  75727. }
  75728. };
  75729. GLTFLoader.prototype._buildInt8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75730. if (!byteStride) {
  75731. return new Int8Array(buffer, byteOffset, byteLength);
  75732. }
  75733. var sourceBuffer = new Int8Array(buffer, byteOffset);
  75734. var targetBuffer = new Int8Array(byteLength);
  75735. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  75736. return targetBuffer;
  75737. };
  75738. GLTFLoader.prototype._buildUint8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75739. if (!byteStride) {
  75740. return new Uint8Array(buffer, byteOffset, byteLength);
  75741. }
  75742. var sourceBuffer = new Uint8Array(buffer, byteOffset);
  75743. var targetBuffer = new Uint8Array(byteLength);
  75744. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  75745. return targetBuffer;
  75746. };
  75747. GLTFLoader.prototype._buildInt16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75748. if (!byteStride) {
  75749. return new Int16Array(buffer, byteOffset, byteLength);
  75750. }
  75751. var sourceBuffer = new Int16Array(buffer, byteOffset);
  75752. var targetBuffer = new Int16Array(byteLength);
  75753. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  75754. return targetBuffer;
  75755. };
  75756. GLTFLoader.prototype._buildUint16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75757. if (!byteStride) {
  75758. return new Uint16Array(buffer, byteOffset, byteLength);
  75759. }
  75760. var sourceBuffer = new Uint16Array(buffer, byteOffset);
  75761. var targetBuffer = new Uint16Array(byteLength);
  75762. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  75763. return targetBuffer;
  75764. };
  75765. GLTFLoader.prototype._buildUint32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75766. if (!byteStride) {
  75767. return new Uint32Array(buffer, byteOffset, byteLength);
  75768. }
  75769. var sourceBuffer = new Uint32Array(buffer, byteOffset);
  75770. var targetBuffer = new Uint32Array(byteLength);
  75771. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  75772. return targetBuffer;
  75773. };
  75774. GLTFLoader.prototype._buildFloat32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75775. if (!byteStride) {
  75776. return new Float32Array(buffer, byteOffset, byteLength);
  75777. }
  75778. var sourceBuffer = new Float32Array(buffer, byteOffset);
  75779. var targetBuffer = new Float32Array(byteLength);
  75780. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  75781. return targetBuffer;
  75782. };
  75783. GLTFLoader.prototype._extractInterleavedData = function (sourceBuffer, targetBuffer, bytePerComponent, stride, length) {
  75784. var tempIndex = 0;
  75785. var sourceIndex = 0;
  75786. var storageSize = bytePerComponent;
  75787. while (tempIndex < length) {
  75788. for (var cursor = 0; cursor < storageSize; cursor++) {
  75789. targetBuffer[tempIndex] = sourceBuffer[sourceIndex + cursor];
  75790. tempIndex++;
  75791. }
  75792. sourceIndex += stride;
  75793. }
  75794. };
  75795. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, bytePerComponent, componentType, onSuccess) {
  75796. var _this = this;
  75797. byteOffset += (bufferView.byteOffset || 0);
  75798. var buffer = this._getArrayItem(this._gltf.buffers, bufferView.buffer, "Buffer");
  75799. if (!buffer) {
  75800. return;
  75801. }
  75802. this._loadBufferAsync(buffer, function (bufferData) {
  75803. if (byteOffset + byteLength > bufferData.byteLength) {
  75804. _this._onError("Buffer access is out of range");
  75805. return;
  75806. }
  75807. var buffer = bufferData.buffer;
  75808. byteOffset += bufferData.byteOffset;
  75809. var bufferViewData;
  75810. switch (componentType) {
  75811. case GLTF2.EComponentType.BYTE:
  75812. bufferViewData = _this._buildInt8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75813. break;
  75814. case GLTF2.EComponentType.UNSIGNED_BYTE:
  75815. bufferViewData = _this._buildUint8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75816. break;
  75817. case GLTF2.EComponentType.SHORT:
  75818. bufferViewData = _this._buildInt16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75819. break;
  75820. case GLTF2.EComponentType.UNSIGNED_SHORT:
  75821. bufferViewData = _this._buildUint16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75822. break;
  75823. case GLTF2.EComponentType.UNSIGNED_INT:
  75824. bufferViewData = _this._buildUint32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75825. break;
  75826. case GLTF2.EComponentType.FLOAT:
  75827. bufferViewData = _this._buildFloat32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75828. break;
  75829. default:
  75830. _this._onError("Invalid component type (" + componentType + ")");
  75831. return;
  75832. }
  75833. onSuccess(bufferViewData);
  75834. });
  75835. };
  75836. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  75837. var bufferView = this._getArrayItem(this._gltf.bufferViews, accessor.bufferView, "Buffer view");
  75838. if (!bufferView) {
  75839. return;
  75840. }
  75841. var byteOffset = accessor.byteOffset || 0;
  75842. var bytePerComponent = this._getByteStrideFromType(accessor);
  75843. var byteLength = accessor.count * bytePerComponent;
  75844. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, bytePerComponent, accessor.componentType, onSuccess);
  75845. };
  75846. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  75847. switch (accessor.type) {
  75848. case "SCALAR": return 1;
  75849. case "VEC2": return 2;
  75850. case "VEC3": return 3;
  75851. case "VEC4": return 4;
  75852. case "MAT2": return 4;
  75853. case "MAT3": return 9;
  75854. case "MAT4": return 16;
  75855. default:
  75856. this._onError("Invalid accessor type (" + accessor.type + ")");
  75857. return 0;
  75858. }
  75859. };
  75860. GLTFLoader.prototype._addPendingData = function (data) {
  75861. if (!this._renderReady) {
  75862. this._renderPendingCount++;
  75863. }
  75864. this._addLoaderPendingData(data);
  75865. };
  75866. GLTFLoader.prototype._removePendingData = function (data) {
  75867. if (!this._renderReady) {
  75868. if (--this._renderPendingCount === 0) {
  75869. this._renderReady = true;
  75870. this._onRenderReady();
  75871. }
  75872. }
  75873. this._removeLoaderPendingData(data);
  75874. };
  75875. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  75876. this._loaderPendingCount++;
  75877. this._loaderTrackers.forEach(function (tracker) { return tracker._addPendingData(data); });
  75878. };
  75879. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  75880. this._loaderTrackers.forEach(function (tracker) { return tracker._removePendingData(data); });
  75881. if (--this._loaderPendingCount === 0) {
  75882. this._onComplete();
  75883. }
  75884. };
  75885. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  75886. var _this = this;
  75887. var tracker = new GLTFLoaderTracker(function () {
  75888. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker));
  75889. onComplete();
  75890. });
  75891. this._loaderTrackers.push(tracker);
  75892. this._addLoaderPendingData(tracker);
  75893. action();
  75894. this._removeLoaderPendingData(tracker);
  75895. };
  75896. GLTFLoader.prototype._getDefaultMaterial = function () {
  75897. if (!this._defaultMaterial) {
  75898. var id = "__gltf_default";
  75899. var material = this._babylonScene.getMaterialByName(id);
  75900. if (!material) {
  75901. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  75902. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  75903. material.metallic = 1;
  75904. material.roughness = 1;
  75905. }
  75906. this._defaultMaterial = material;
  75907. }
  75908. return this._defaultMaterial;
  75909. };
  75910. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  75911. var babylonMaterial = material.babylonMaterial;
  75912. // Ensure metallic workflow
  75913. babylonMaterial.metallic = 1;
  75914. babylonMaterial.roughness = 1;
  75915. var properties = material.pbrMetallicRoughness;
  75916. if (!properties) {
  75917. return;
  75918. }
  75919. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  75920. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  75921. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  75922. if (properties.baseColorTexture) {
  75923. babylonMaterial.albedoTexture = this._loadTexture(properties.baseColorTexture);
  75924. }
  75925. if (properties.metallicRoughnessTexture) {
  75926. babylonMaterial.metallicTexture = this._loadTexture(properties.metallicRoughnessTexture);
  75927. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  75928. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  75929. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  75930. }
  75931. this._loadMaterialAlphaProperties(material, properties.baseColorFactor);
  75932. };
  75933. GLTFLoader.prototype._loadMaterial = function (material, assign) {
  75934. if (material.babylonMaterial) {
  75935. assign(material.babylonMaterial, false);
  75936. return;
  75937. }
  75938. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  75939. return;
  75940. }
  75941. this._createPbrMaterial(material);
  75942. this._loadMaterialBaseProperties(material);
  75943. this._loadMaterialMetallicRoughnessProperties(material);
  75944. assign(material.babylonMaterial, true);
  75945. };
  75946. GLTFLoader.prototype._createPbrMaterial = function (material) {
  75947. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  75948. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  75949. material.babylonMaterial = babylonMaterial;
  75950. };
  75951. GLTFLoader.prototype._loadMaterialBaseProperties = function (material) {
  75952. var babylonMaterial = material.babylonMaterial;
  75953. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  75954. if (material.doubleSided) {
  75955. babylonMaterial.backFaceCulling = false;
  75956. babylonMaterial.twoSidedLighting = true;
  75957. }
  75958. if (material.normalTexture) {
  75959. babylonMaterial.bumpTexture = this._loadTexture(material.normalTexture);
  75960. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  75961. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  75962. if (material.normalTexture.scale !== undefined) {
  75963. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  75964. }
  75965. }
  75966. if (material.occlusionTexture) {
  75967. babylonMaterial.ambientTexture = this._loadTexture(material.occlusionTexture);
  75968. babylonMaterial.useAmbientInGrayScale = true;
  75969. if (material.occlusionTexture.strength !== undefined) {
  75970. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  75971. }
  75972. }
  75973. if (material.emissiveTexture) {
  75974. babylonMaterial.emissiveTexture = this._loadTexture(material.emissiveTexture);
  75975. }
  75976. };
  75977. GLTFLoader.prototype._loadMaterialAlphaProperties = function (material, colorFactor) {
  75978. var babylonMaterial = material.babylonMaterial;
  75979. var alphaMode = material.alphaMode || "OPAQUE";
  75980. switch (alphaMode) {
  75981. case "OPAQUE":
  75982. // default is opaque
  75983. break;
  75984. case "MASK":
  75985. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  75986. if (colorFactor) {
  75987. if (colorFactor[3] == 0) {
  75988. babylonMaterial.alphaCutOff = 1;
  75989. }
  75990. else {
  75991. babylonMaterial.alphaCutOff /= colorFactor[3];
  75992. }
  75993. }
  75994. if (babylonMaterial.albedoTexture) {
  75995. babylonMaterial.albedoTexture.hasAlpha = true;
  75996. }
  75997. break;
  75998. case "BLEND":
  75999. if (colorFactor) {
  76000. babylonMaterial.alpha = colorFactor[3];
  76001. }
  76002. if (babylonMaterial.albedoTexture) {
  76003. babylonMaterial.albedoTexture.hasAlpha = true;
  76004. babylonMaterial.useAlphaFromAlbedoTexture = true;
  76005. }
  76006. break;
  76007. default:
  76008. this._onError("Invalid alpha mode '" + material.alphaMode + "'");
  76009. return;
  76010. }
  76011. };
  76012. GLTFLoader.prototype._loadTexture = function (textureInfo) {
  76013. var _this = this;
  76014. var texture = this._getArrayItem(this._gltf.textures, textureInfo.index, "Texture");
  76015. if (!texture) {
  76016. return null;
  76017. }
  76018. var texCoord = textureInfo.texCoord || 0;
  76019. var source = this._getArrayItem(this._gltf.images, texture.source, "Texture (" + textureInfo.index + ") source");
  76020. if (!source) {
  76021. return null;
  76022. }
  76023. var sampler = (texture.sampler == null ? {} : this._getArrayItem(this._gltf.samplers, texture.sampler, "Texture (" + textureInfo.index + ") sampler"));
  76024. if (!sampler) {
  76025. return;
  76026. }
  76027. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  76028. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  76029. this._addPendingData(texture);
  76030. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  76031. if (!_this._disposed) {
  76032. _this._removePendingData(texture);
  76033. }
  76034. }, function () {
  76035. if (!_this._disposed) {
  76036. _this._onError("Failed to load texture '" + source.uri + "'");
  76037. _this._removePendingData(texture);
  76038. }
  76039. });
  76040. if (texture.url) {
  76041. babylonTexture.updateURL(texture.url);
  76042. }
  76043. else if (texture.dataReadyObservable) {
  76044. texture.dataReadyObservable.add(function (texture) {
  76045. babylonTexture.updateURL(texture.url);
  76046. });
  76047. }
  76048. else {
  76049. texture.dataReadyObservable = new BABYLON.Observable();
  76050. texture.dataReadyObservable.add(function (texture) {
  76051. babylonTexture.updateURL(texture.url);
  76052. });
  76053. var setTextureData = function (data) {
  76054. texture.url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  76055. texture.dataReadyObservable.notifyObservers(texture);
  76056. };
  76057. if (!source.uri) {
  76058. var bufferView = this._getArrayItem(this._gltf.bufferViews, source.bufferView, "Texture (" + textureInfo.index + ") source (" + texture.source + ") buffer view");
  76059. if (!bufferView) {
  76060. return;
  76061. }
  76062. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, 1, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  76063. }
  76064. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  76065. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  76066. }
  76067. else {
  76068. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  76069. _this._onProgress(event);
  76070. }, this._babylonScene.database, true, function (request) {
  76071. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  76072. });
  76073. }
  76074. }
  76075. babylonTexture.coordinatesIndex = texCoord;
  76076. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  76077. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  76078. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  76079. if (this._parent.onTextureLoaded) {
  76080. this._parent.onTextureLoaded(babylonTexture);
  76081. }
  76082. return babylonTexture;
  76083. };
  76084. GLTFLoader.prototype._getArrayItem = function (array, index, name) {
  76085. if (!array || !array[index]) {
  76086. this._onError(name + " index (" + index + ") was not found");
  76087. return null;
  76088. }
  76089. return array[index];
  76090. };
  76091. return GLTFLoader;
  76092. }());
  76093. GLTFLoader.Extensions = {};
  76094. GLTF2.GLTFLoader = GLTFLoader;
  76095. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  76096. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76097. })(BABYLON || (BABYLON = {}));
  76098. //# sourceMappingURL=babylon.glTFLoader.js.map
  76099. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76100. var BABYLON;
  76101. (function (BABYLON) {
  76102. var GLTF2;
  76103. (function (GLTF2) {
  76104. /**
  76105. * Utils functions for GLTF
  76106. */
  76107. var GLTFUtils = (function () {
  76108. function GLTFUtils() {
  76109. }
  76110. /**
  76111. * If the uri is a base64 string
  76112. * @param uri: the uri to test
  76113. */
  76114. GLTFUtils.IsBase64 = function (uri) {
  76115. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  76116. };
  76117. /**
  76118. * Decode the base64 uri
  76119. * @param uri: the uri to decode
  76120. */
  76121. GLTFUtils.DecodeBase64 = function (uri) {
  76122. var decodedString = atob(uri.split(",")[1]);
  76123. var bufferLength = decodedString.length;
  76124. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  76125. for (var i = 0; i < bufferLength; i++) {
  76126. bufferView[i] = decodedString.charCodeAt(i);
  76127. }
  76128. return bufferView.buffer;
  76129. };
  76130. GLTFUtils.ForEach = function (view, func) {
  76131. for (var index = 0; index < view.length; index++) {
  76132. func(view[index], index);
  76133. }
  76134. };
  76135. GLTFUtils.GetTextureWrapMode = function (mode) {
  76136. // Set defaults if undefined
  76137. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  76138. switch (mode) {
  76139. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  76140. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  76141. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  76142. default:
  76143. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  76144. return BABYLON.Texture.WRAP_ADDRESSMODE;
  76145. }
  76146. };
  76147. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  76148. // Set defaults if undefined
  76149. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  76150. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  76151. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  76152. switch (minFilter) {
  76153. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  76154. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  76155. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  76156. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  76157. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  76158. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  76159. default:
  76160. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  76161. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  76162. }
  76163. }
  76164. else {
  76165. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  76166. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  76167. }
  76168. switch (minFilter) {
  76169. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  76170. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  76171. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  76172. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  76173. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  76174. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  76175. default:
  76176. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  76177. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  76178. }
  76179. }
  76180. };
  76181. /**
  76182. * Decodes a buffer view into a string
  76183. * @param view: the buffer view
  76184. */
  76185. GLTFUtils.DecodeBufferToText = function (view) {
  76186. var result = "";
  76187. var length = view.byteLength;
  76188. for (var i = 0; i < length; ++i) {
  76189. result += String.fromCharCode(view[i]);
  76190. }
  76191. return result;
  76192. };
  76193. return GLTFUtils;
  76194. }());
  76195. GLTF2.GLTFUtils = GLTFUtils;
  76196. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76197. })(BABYLON || (BABYLON = {}));
  76198. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  76199. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76200. var BABYLON;
  76201. (function (BABYLON) {
  76202. var GLTF2;
  76203. (function (GLTF2) {
  76204. var GLTFLoaderExtension = (function () {
  76205. function GLTFLoaderExtension() {
  76206. this.enabled = true;
  76207. }
  76208. GLTFLoaderExtension.prototype._traverseNode = function (loader, index, action, parentNode) { return false; };
  76209. GLTFLoaderExtension.prototype._loadNode = function (loader, node) { return false; };
  76210. GLTFLoaderExtension.prototype._loadMaterial = function (loader, material, assign) { return false; };
  76211. GLTFLoaderExtension.prototype._loadExtension = function (property, action) {
  76212. var _this = this;
  76213. if (!property.extensions) {
  76214. return false;
  76215. }
  76216. var extension = property.extensions[this.name];
  76217. if (!extension) {
  76218. return false;
  76219. }
  76220. // Clear out the extension before executing the action to avoid recursing into the same property.
  76221. property.extensions[this.name] = undefined;
  76222. action(extension, function () {
  76223. // Restore the extension after completing the action.
  76224. property.extensions[_this.name] = extension;
  76225. });
  76226. return true;
  76227. };
  76228. GLTFLoaderExtension.TraverseNode = function (loader, index, action, parentNode) {
  76229. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, index, action, parentNode); });
  76230. };
  76231. GLTFLoaderExtension.LoadNode = function (loader, node) {
  76232. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, node); });
  76233. };
  76234. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  76235. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, material, assign); });
  76236. };
  76237. GLTFLoaderExtension._ApplyExtensions = function (action) {
  76238. var extensions = GLTFLoaderExtension._Extensions;
  76239. if (!extensions) {
  76240. return;
  76241. }
  76242. for (var i = 0; i < extensions.length; i++) {
  76243. var extension = extensions[i];
  76244. if (extension.enabled && action(extension)) {
  76245. return true;
  76246. }
  76247. }
  76248. return false;
  76249. };
  76250. return GLTFLoaderExtension;
  76251. }());
  76252. //
  76253. // Utilities
  76254. //
  76255. GLTFLoaderExtension._Extensions = [];
  76256. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  76257. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76258. })(BABYLON || (BABYLON = {}));
  76259. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  76260. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  76261. var BABYLON;
  76262. (function (BABYLON) {
  76263. var GLTF2;
  76264. (function (GLTF2) {
  76265. var Extensions;
  76266. (function (Extensions) {
  76267. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  76268. var MSFTLOD = (function (_super) {
  76269. __extends(MSFTLOD, _super);
  76270. function MSFTLOD() {
  76271. return _super !== null && _super.apply(this, arguments) || this;
  76272. }
  76273. Object.defineProperty(MSFTLOD.prototype, "name", {
  76274. get: function () {
  76275. return "MSFT_lod";
  76276. },
  76277. enumerable: true,
  76278. configurable: true
  76279. });
  76280. MSFTLOD.prototype._traverseNode = function (loader, index, action, parentNode) {
  76281. var node = loader._getArrayItem(loader._gltf.nodes, index, "Node");
  76282. if (!node) {
  76283. return true;
  76284. }
  76285. return this._loadExtension(node, function (extension, onComplete) {
  76286. for (var i = extension.ids.length - 1; i >= 0; i--) {
  76287. loader._traverseNode(extension.ids[i], action, parentNode);
  76288. }
  76289. loader._traverseNode(index, action, parentNode);
  76290. onComplete();
  76291. });
  76292. };
  76293. MSFTLOD.prototype._loadNode = function (loader, node) {
  76294. var _this = this;
  76295. return this._loadExtension(node, function (extension, onComplete) {
  76296. var nodes = [node.index].concat(extension.ids).map(function (index) { return loader._gltf.nodes[index]; });
  76297. loader._addLoaderPendingData(node);
  76298. _this._loadNodeLOD(loader, nodes, nodes.length - 1, function () {
  76299. loader._removeLoaderPendingData(node);
  76300. onComplete();
  76301. });
  76302. });
  76303. };
  76304. MSFTLOD.prototype._loadNodeLOD = function (loader, nodes, index, onComplete) {
  76305. var _this = this;
  76306. loader._whenAction(function () {
  76307. loader._loadNode(nodes[index]);
  76308. }, function () {
  76309. if (index !== nodes.length - 1) {
  76310. var previousNode = nodes[index + 1];
  76311. previousNode.babylonMesh.setEnabled(false);
  76312. }
  76313. if (index === 0) {
  76314. onComplete();
  76315. return;
  76316. }
  76317. setTimeout(function () {
  76318. _this._loadNodeLOD(loader, nodes, index - 1, onComplete);
  76319. }, MSFTLOD.MinimalLODDelay);
  76320. });
  76321. };
  76322. MSFTLOD.prototype._loadMaterial = function (loader, material, assign) {
  76323. var _this = this;
  76324. return this._loadExtension(material, function (extension, onComplete) {
  76325. var materials = [material.index].concat(extension.ids).map(function (index) { return loader._gltf.materials[index]; });
  76326. loader._addLoaderPendingData(material);
  76327. _this._loadMaterialLOD(loader, materials, materials.length - 1, assign, function () {
  76328. material.extensions[_this.name] = extension;
  76329. loader._removeLoaderPendingData(material);
  76330. onComplete();
  76331. });
  76332. });
  76333. };
  76334. MSFTLOD.prototype._loadMaterialLOD = function (loader, materials, index, assign, onComplete) {
  76335. var _this = this;
  76336. loader._loadMaterial(materials[index], function (babylonMaterial, isNew) {
  76337. assign(babylonMaterial, isNew);
  76338. if (index === 0) {
  76339. onComplete();
  76340. return;
  76341. }
  76342. // Load the next LOD when the loader is ready to render and
  76343. // all active material textures of the current LOD are loaded.
  76344. loader._executeWhenRenderReady(function () {
  76345. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  76346. setTimeout(function () {
  76347. _this._loadMaterialLOD(loader, materials, index - 1, assign, onComplete);
  76348. }, MSFTLOD.MinimalLODDelay);
  76349. });
  76350. });
  76351. });
  76352. };
  76353. return MSFTLOD;
  76354. }(GLTF2.GLTFLoaderExtension));
  76355. /**
  76356. * Specify the minimal delay between LODs in ms (default = 250)
  76357. */
  76358. MSFTLOD.MinimalLODDelay = 250;
  76359. Extensions.MSFTLOD = MSFTLOD;
  76360. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  76361. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  76362. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76363. })(BABYLON || (BABYLON = {}));
  76364. //# sourceMappingURL=MSFT_lod.js.map
  76365. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  76366. var BABYLON;
  76367. (function (BABYLON) {
  76368. var GLTF2;
  76369. (function (GLTF2) {
  76370. var Extensions;
  76371. (function (Extensions) {
  76372. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  76373. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  76374. function KHRMaterialsPbrSpecularGlossiness() {
  76375. return _super !== null && _super.apply(this, arguments) || this;
  76376. }
  76377. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  76378. get: function () {
  76379. return "KHR_materials_pbrSpecularGlossiness";
  76380. },
  76381. enumerable: true,
  76382. configurable: true
  76383. });
  76384. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, material, assign) {
  76385. var _this = this;
  76386. return this._loadExtension(material, function (extension, onComplete) {
  76387. loader._createPbrMaterial(material);
  76388. loader._loadMaterialBaseProperties(material);
  76389. _this._loadSpecularGlossinessProperties(loader, material, extension);
  76390. assign(material.babylonMaterial, true);
  76391. });
  76392. };
  76393. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  76394. var babylonMaterial = material.babylonMaterial;
  76395. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  76396. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  76397. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  76398. if (properties.diffuseTexture) {
  76399. babylonMaterial.albedoTexture = loader._loadTexture(properties.diffuseTexture);
  76400. }
  76401. if (properties.specularGlossinessTexture) {
  76402. babylonMaterial.reflectivityTexture = loader._loadTexture(properties.specularGlossinessTexture);
  76403. babylonMaterial.reflectivityTexture.hasAlpha = true;
  76404. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  76405. }
  76406. loader._loadMaterialAlphaProperties(material, properties.diffuseFactor);
  76407. };
  76408. return KHRMaterialsPbrSpecularGlossiness;
  76409. }(GLTF2.GLTFLoaderExtension));
  76410. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  76411. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  76412. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  76413. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76414. })(BABYLON || (BABYLON = {}));
  76415. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  76416. (function universalModuleDefinition(root, factory) {
  76417. if (root && root["BABYLON"]) {
  76418. return;
  76419. }
  76420. if(typeof exports === 'object' && typeof module === 'object')
  76421. module.exports = factory();
  76422. else if(typeof define === 'function' && define.amd)
  76423. define([], factory);
  76424. else if(typeof exports === 'object')
  76425. exports["BABYLON"] = factory();
  76426. else {
  76427. root["BABYLON"] = factory();
  76428. }
  76429. })(this, function() {
  76430. return BABYLON;
  76431. });